
/*!
 * X weibo JavaScript Library v1.2
 * http://x.weibo.com/
 * 
 * Copyright 2011 SINA Inc.
 */
 
/*
 * 页面初始化文件，该文件存放页面所有的Pagelet类或派生类实例。
 */

(function(X, $){
    var getCfg = X.getCfg,
        Req = X.request,
        Util = X.util,
        Box = X.ui.MsgBox,
        Pagelet = X.ax.Pagelet,
        getText = X.lang.getText,
        UNDEFINED = undefined,
		T = X.ax.Tpl,
        pipe = X.use('pipeMgr'),
        mod = X.mod;
		        
    /**
     * @namespace
     * 存放所有继承{@link Xwb.ax.Pagelet}类
     */
    Util.ns('Xwb.mod.pagelet', {});
var SpotsPipe = {
            ui : {
                actionMgr : true,
                
                onactiontrig : function(e) {
                    switch (e.data.e) {
                    case 'sp':
                        var wid = e.get('w'),
                            wb = wid && X.getWb(wid);
                            
                        wb && this.showPic(wb);
                    break;
                    default:
                        e.sid = this.spots && this.spots.id;
                        e.stopPropagation(0);
                    }
                },
                
                //示图片
                showPic : function(wb) {
                    var box = X.use('ImageShow');
					
                    box.display(1)
                    .load(wb);
					box.setOffset();
                },
                
                
                mouseover : function(e) {
                    var $item = $(e.target).closest('DIV.feed-box');
                    $item.length && $item.find('.operation-area').cssDisplay(1);
                },

                mouseout : function(e) {
                    var $target = $(e.target);
                    var $item = $target.closest('div.feed-box');
                    if ($item.length) {
                        var $related = $(e.relatedTarget);

                        if (!$related || !$.contains($item[0], $related[0]) ) {
                            $item.find('div.operation-area').cssDisplay(0);
                        }
                    }
                }

            },
            
            cols : [],
            
            //data : {},
            
            itemLength: 0,
            
            onViewReady : function(cfg){
				
				var pagelet = {'spots.wbBox' : {url : Req.getFeedTimeline, times : 1000, pageSize : 25},
				  'spotsWb.cityWbBox' : {url : Req.getFeedTimeline, times : 1000, pageSize : 25},
				  'spots.common_spot_dynamics' : {url : '', times : 4, pageSize : 10},
				  'weiboapp.weiboList' : {url : Req.getWeiboLists, times : 4, pageSize : 10}//微博直播
				  }
				  
				var curPagelet = pagelet[cfg.pagelet];
				this.pageName = cfg.pagelet;
				this.times = curPagelet.times;
				this.getDataUrl = curPagelet.url;
				this.pageSize = curPagelet.pageSize;
				
                var ui = this.getUI(),
                    data = cfg.data;
                this.max_id = data.max_id;
				this.pageSize = 25;
				
				this.hasNextPage = data.wbs.length<this.pageSize?true:true;
                //建立spots映射
                this.spots = data.spots;
                X.cfg.spots = ui.spots = this.spots;

                var loading = this.loading = ui.jq('#sloading');
                var cols = this.cols = [
                    ui.jq('#col_1'),
                    ui.jq('#col_2'),
                    ui.jq('#col_3'),
                    ui.jq('#col_4')
                ];
				this.colCount = 4;

                var htmls = data.wbs_html;
				this.wbCount = htmls.length;
                
                X.addWb(data.wbs);
					
				if( data.wbs.length !== 0){
					loading.cssDisplay(0);
				    this.createItems( htmls, Util.getBind(this, 'toLoadedSeq'));
				}
                else{
					$('#feedList').after('<div align="center">没有数据</div>');
					loading.cssDisplay(0);
				}

				
				//景区内喜欢
				X.on('api.likeSpots',function(data){
					var reqdata = data.reqCfg.data;
					var wbDiv = ui.jq('div[rel="w:'+reqdata.wb_id+',s:'+reqdata.spots_id+'"]');
					if(X.getCfg('wbList')[reqdata.wb_id]){
						var wb = X.getCfg('wbList')[reqdata.wb_id];
						var elem = wbDiv.find('a[rel="e:like"]');
						elem.attr('class',wb.whether_liked ? 'ico-liked' : 'ico-like');
						elem.find('em').html(wb.like_count);
					}
				});
				//景区内评论
				X.on('api.comment',function(data){
					var wb_id = data.reqCfg.data.id;
					var wbDiv = ui.jq('div[rel="w:'+wb_id+',s:'+X.getCfg('spots').id+'"]');
					if(X.getCfg('wbList')[wb_id]){
						var wb = X.getCfg('wbList')[wb_id];
						var elem = wbDiv.find('a[rel="e:scm"]');
						elem.attr('class',wb.comments_count ? 'ico-commented' : 'ico-comment');
						elem.find('em').html(wb.comments_count);
					}
				});
            },
			/**
            * @param {Array} HTML结构
            * @param [loadFn] 加载完成后
            */
            createItems : function( htmls, loadFn ){
                $.each(htmls, function(i, html){
                    var item = X.use('SpotItem', {
                        html: html,
                        onload : function(succ, view ){
                            loadFn && loadFn( view );
                        }
                    });
                });
            },
			//等待wb里的图片加载完后，逐个插入到页面
			loadedWbSeq : [],
			loadedCount : 0,
			toLoadedSeq : function( wb ){
				var $img = wb.find('#pvImg>img');
			    var imgh = $img[0].height;  //img自身高度
				if( imgh > 500 )
				    $img.parent().css('height',500);
				wb.calcH = imgh;
				wb.calcH += 18*Math.floor( wb.find('p').html().length/15 ); //文本高度
				this.binaryInsert( this.loadedWbSeq, 0, this.loadedWbSeq.length-1, wb );
				
				var self = this;
				if( ++this.loadedCount < 4 )
					setTimeout( function(){ self.insertWbToPage(); },800); //头4个延迟800ms
				else self.insertWbToPage(); 
			},
			binaryInsert : function( wbArr, l, r, wb ){  //二分插入 
			    if( l === r || r <= 0){
				    if( wbArr.length !== 0 ) 
						wb.calcH < wbArr[l].calcH ? wbArr.splice(l,0,wb) : wbArr.splice(l+1,0,wb);
				    else 
					    wbArr.push( wb );
					return ;
				}
				var mid = Math.floor( (l + r)/2 );
				if( wb.calcH < wbArr[mid].calcH ){
				    this.binaryInsert( wbArr, l, mid-1, wb );
				}
				else if ( wb.calcH > wbArr[mid].calcH ){
				    this.binaryInsert( wbArr, mid+1, r, wb );
				}
				else {
				    wbArr.splice(mid, 0, wb);
				}
			},
			insertWbToPage : function(){
				var cols = this.cols,
				    tarCol = 0;
				for(var i = 1; i<this.colCount; i++){
				    if( cols[tarCol].height() > cols[i].height() )
						tarCol = i;    //取最小的列
				}
				
				var wb = this.loadedWbSeq.pop();
				if(!Util.ie6) wb.css('opacity',0);
				this.cols[ tarCol ].append(wb);  //取最后一个
				if(!Util.ie6) wb.animate({'opacity': 1},600);
				if(  --this.wbCount === 0 && this.hasNextPage){
					//debugger;
				    this.loadedCount = 0;
					this.hideLoading();
					this.adjust();
					this.enScroll = true;
					this.setScrollLoad();
				}
			},
			adjust : function(){
			},
			enScroll : false,
			times : 1000,   //可滚动次数
			setScrollLoad : function(){
			    var self = this;
			 	$(window).bind('scroll',function(){
				    if( !self.enScroll || self.times <= 0 ) return ;
					if( $(document).scrollTop() + Util.getClientHeight() > $(document.body).height() - 50 ){						
						self.enScroll = false;
						self.showLoading();
						if(self.pageName == 'weiboapp.weiboList')
							self.getDataUrl.call(Req,{page : 4 - self.times + 2 },function(r){
								self.enScroll = true;
								self.hideLoading();
								if(r.isOk()){
									var data = r.getData();
									if(data.wbs.length == 0){
										self.hasNextPage = false;
										$(window).unbind('scroll');
										return;
									}
									self.hasNextPage = data.wbs.length<self.pageSize?false:true;
									X.addWb(data.wbs);								
									self.times--;
									self.createItems( data.wbs_html, Util.getBind( self, 'toLoadedSeq'));
								} else {
									self.hasNextPage = false;
									$(window).unbind('scroll');
								}
							})
						else						
							self.getDataUrl.call(Req, {spots_id:self.spots.id, max_id:self.max_id, count:self.pageSize} ,function(r){
								self.enScroll = true;
								self.hideLoading();
								if(r.isOk()){
									var data = r.getData();
									if(data.max_id == null || data.max_id == '' || data.wbs.length == 0){
										self.hasNextPage = false;
										$(window).unbind('scroll');
										return;
									}
									self.max_id = data.max_id;
									self.hasNextPage = data.wbs.length<self.pageSize?false:true;
									X.addWb(data.wbs);								
									self.times--;
									self.createItems( data.wbs_html, Util.getBind( self, 'toLoadedSeq'));
								} else {
									self.hasNextPage = false;
									$(window).unbind('scroll');
								}
							});
					}
				});
			},
		
            showLoading : function() {
                this.loading.cssDisplay(1);                
            },
            
            hideLoading : function() {
                this.loading.cssDisplay(0);
            }
        };

var CommentPipe = Util.create(Pagelet, {
    ui : {},
    onViewReady : function(cfg) {
        var data = cfg.data;
        
        var cmt = this.cmt = X.use('CmtArea', {
        wbId :  data.id,
        wbUid :  data.uid,
        newSystem : true,
        profileImg : getCfg('face_m') || '/img/default.png',
        appendTo: this.jq(),
        trigEl : '#b_comment',
        type : 'youji',
        maxLen: 280,
        showReply : false,
        pagecount : 10,
        localComments : true,
        getCommentUrl : Req.getZyjComment,
        commentUrl : Req.zyjComment,
        delComment : Req.delZyjComment,
        
        onViewReady : function() {
            var focusCS = 'style-focus';
            this.jq('textarea').bind({
                focus: function(){
                    $(this).addClass(focusCS)
                },
                blur : function(){
                    $(this).removeClass(focusCS);
                }
            })
            
            var args = X.cfg.args, self = this;
            if(args && args.id && args.nick)//点回复跳转过来
                X.on('commentsApi.getComments',function(e){
                    self.cmtBox.reply(args.cid, args.nick);
                    X.un('commentsApi.getComments');
                });    

        },
        
        afterShow : function() {
            //检测url Hash ，如果是comment，则focus到输入框
            if (location.hash == '#comment') {
                $(document).scrollTop(this.jq().offset().top-75);
                this.jq('textarea').focus();
            }
        }
    });
    cmt.display(1);
    cmt.load();
    }
})
	
    
    /**
     * @class Xwb.mod.pagelet.WeiboList
     * 微博列表块基类
     * @extends Xwb.ax.Pagelet
     */
    var WBPipe = X.mod.pagelet.WeiboList = Util.create(Pagelet, {
        
        // 页块的UI类
        ui : {cls:X.mod.WeiboList},
        
        wbSelector : '#xwb_weibo_list_ct>li',
        
        // 回调返回html作为页面内容
        onViewReady : function(cfg){
        	
            var d = cfg.data;
            if(d){
                // 微博数据对象
                var ls = d.list;
                if(ls){
                    var gls = X.cfg.wbList;
                    if(!gls)
                        X.cfg.wbList = gls = {};
                    // 添加到全局微博数据缓存
                    for(var id in ls){
                        if(!gls[id])
                            gls[id] = ls[id];
                    }
                }
                
                // 监听全局微博计数返回事件
                X.on('api.getCounts', Util.getBind(this, 'onUpdateCounter'));
            }
        },

        onUpdateCounter : function(e){
            if(e.isOk()){
                var wbs = this.getUI().jq(this.wbSelector ? this.wbSelector : UNDEFINED),
                    wbsData = X.cfg.wbList,
                    cntData = e.getData();
                var jq, wid, wbd, cntd;
                var self = this;
                wbs.each(function(){
                    jq   = $(this);
                    wid  = Util.parseKnV(jq.attr('rel')).w;
                    cntd = cntData[wid];
                    // 自身微博
                    if(cntd)
                        self.renderWeiboCounter(jq, cntd);
                    
                    // 内容转发区内的微博
                    wbd  = wbsData[wid];
                    if (wbd){
                        var rt = wbd.rt;
                        if(rt && (cntd = cntData[rt.id])){
                            jq = jq.find('.forward');
                            self.renderInnerWeiboCounter(jq, cntd);
                        }
                    }
                });
            }
        },
        
        // 自身微博数据更新
        renderWeiboCounter : function(jq, cntd){
            // 存在评论
            if(cntd[0])
                jq.find('#cm').text( getText('评论') + '(' + cntd[0] + ')');
            // 存在转发
            if(cntd[1])
                jq.find('#fw').text( getText('转发') + '(' + cntd[1] + ')');
        },
        
        // 内容转发区内的微博数据更新
        renderInnerWeiboCounter : function(jq, cntd){
            // 存在评论
            if(cntd[0])
                jq.find('#lk_cm').text( getText('原文评论') + '(' + cntd[0] + ')');
            // 存在转发
            if(cntd[1])
                jq.find('#lk_fw').text( getText('原文转发') + '(' + cntd[1] + ')');
        }
    });

    //
    //
    //
    
	        // 我的评论页，MyCmt类在mycomments.js中
        // 此时X.mod.MyCmt还未加载，所以放到一个函数中返回，
        // 当调用的时候就加载好了
        pipe.reg('weibo.comments', function(v){
            return new Pagelet( {
                
                onViewReady : function(cfg) {

                    var data = cfg.data,
                        ui = this.getUI(),
						youjiId = getCfg('youji') ? getCfg('youji').id : undefined;
                    var cmt = X.use('CmtArea', {
                        wbId :  youjiId ? youjiId : data.wbid,
                        wbUid :  youjiId ? getCfg('youji').user.id :data.wbuid,
						newSystem : true,
						profileImg : getCfg('face_m') || '/img/default.png',
                        appendTo: ui.jq(),
                        trigEl : '#b_comment',
						type : 'youji',
						maxLen: cfg.pagelet == "youji.commentBox" ? 200*2 : 140*2,
						localComments : youjiId ? true : false,
                        getCommentUrl : Req.getYoujiComments,
						commentUrl : Req.youjiComment,
						replyUrl : Req.youjiReply,
                        onViewReady : function() {
                            var focusCS = 'style-focus';
                            this.jq('textarea').bind({
                                focus: function(){
                                    $(this).addClass(focusCS)
                                },
                                blur : function(){
                                    $(this).removeClass(focusCS);
                                }
                            })
							
							var args = X.cfg.args, self = this;
							if(args && args.id && args.nick)//点回复跳转过来
								X.on('commentsApi.getComments',function(e){
									self.cmtBox.reply(args.cid, args.nick);
									X.un('commentsApi.getComments');
								});	
	
                        },
                        
                        afterShow : function() {
                            //检测url Hash ，如果是comment，则focus到输入框
                            if (location.hash == '#comment') {
								$(document).scrollTop(this.jq().offset().top-75);
                                this.jq('textarea').focus();
                            }
                        }
                    });
                    cmt.display(1);
                    cmt.load();

                    X.cfg.cmt = cmt;
					//读取发表成功加分提醒					
					Req.getRemindStatus({type:'yj.new'},function(e){
						if(e.isOk()){
							var str = e.getData();
							if(str) 
								X.use('CoinExperience',{notice :str});
								//Box.extTip('<div class="win-success win-fixed">'+str+'</div>','');
						}
					});
                }
            } );
        })
		.reg('youji.commentBox',pipe.pages['weibo.comments'])
        //风景页
        .reg('spots.wbBox', Util.create(Pagelet, SpotsPipe))
        .reg('spotsWb.cityWbBox', Util.create(Pagelet, SpotsPipe))
		//微博直播
		.reg('weiboapp.weiboList', Util.create(Pagelet, SpotsPipe))
		
		//微博直播google地图
		.reg('weiboapp.weiboMap',{
			onViewReady : function(cfg) { 
				X.on('pipe.end', function(){	
					//异步加载google地图，fn为回调
					X.use('LoadGoogleMap').initUI(null, this, null, function(){						
						X.reg('CustomMarker', CustomMarker)
						function CustomMarker(cfg) {
							 this.latlng_ = new google.maps.LatLng(cfg.data.lat,cfg.data.lng);
							 this.data = cfg.data;
							 this.direction = cfg.direction;
							 this.setMap(cfg.map);
							 
						}
						CustomMarker.prototype = new google.maps.OverlayView();
						CustomMarker.prototype.getTime = function(t){
							var s = (Math.round(+new Date)/1000 - t) 
							if(s < 60){
								return Math.round(s)+'秒前'
							}
							if(s < 3600){
								return Math.round(s/60)+'分钟前';
							}
							if(s < 86400){
								return Math.round(s/3600)+'小时前';
							}
							return Math.round(s/86400)+'天前';
						}
						CustomMarker.prototype.draw = function() {	
							var overlayProjection = this.getProjection(),
								latLng = overlayProjection.fromLatLngToDivPixel(this.latlng_),
								div = this.div_,
								data = this.data,
								panes = this.getPanes(),
								that = this,
								randomNum,
								callback = this.callback,
								arr;
								
							if (!div) {
								div = this.div_ = document.createElement('DIV');
								var img = document.createElement('IMG');
								var time = this.getTime(data.create_time);
								$(img).attr('src', data.cover_thumb)
									.attr('title', data.name)
									.attr('alt', data.name);								
								
								this.direction[0] ? arr = {width:74, height:74} : arr = {width:46, height:46}; 
								div.innerHTML = "<div class=\"weibo-live\" "
								+ (that.direction[1] ? "style='left:0'" : "style='right:0'" )
								+ "><div class=\"info\"><p class=\"pic\"><a href=\"#\"></a></p><p class=\"time\">"
								+ time
								+ "</p></div><p class=\"arrow-s"
								+ (that.direction[1] ? 2 : 1)
								+"\"><i></i></p></div>";
								
								$(div).find("a").attr('href', data.spots_url)
									.append(img)										
									.attr('target', '_blank')
									.css('width', arr.width)
									.css('height', arr.height);
								$(div).css('position', 'absolute')
									.css('left', that.direction[2] ? latLng.x + that.direction[2] : latLng.x + 'px')
									.css('top', that.direction[2] ? latLng.y + that.direction[2] : latLng.y + 'px');
								panes.overlayImage.appendChild(div);
								Util.drawImage(img, 100000, 100000, function(obj){		
									if(obj.height >= obj.width){
										var set = arr.width*(obj.height/obj.width);
										$(img).css('width', arr.width + 'px')
											.attr('width', arr.width)
											.attr('height', set);
									}else{
										var set = arr.height*(obj.width/obj.height);
										$(img).css('height', arr.width + 'px')
											.attr('height', arr.width)
											.attr('width', set);
									}
								});
								
							}
							CustomMarker.prototype.remove = function() {
								if (this.div_) {
									this.div_.parentNode.removeChild(this.div_);
									this.div_ = null;
								}
							};
							CustomMarker.prototype.getPosition = function() {
								return this.latlng_;
							};
						}
						
						X.reg('weiboLive', weiboLive);
						function weiboLive(cfg){ 
							this.init(cfg);
						}
						weiboLive.prototype = {
							init : function(cfg){
								this.cfg = cfg;
								this.data = cfg.data;
								this.map = new google.maps.Map(document.getElementById(cfg.mapId), cfg.mapCfg);
								this.area = this.data.spots_ids;
								this.list = [];
								this.temp = this.data.feeds;
								this.formatWb();	
								this.getData(5);				
								var _this = this;
								setTimeout(function(){_this.start()}, 1000); //draw函数延迟，start延迟执行
							},
							start : function(){
								if(this.list.length){
									var _this = this;
									_this._disPic();
									setInterval(function(){
										if(_this.tempReady){
											_this.formatWb();
											_this.tempReady = 0;
										}										
										if(_this.getCount() > 60){
											_this.deleteData(60);
										}
										_this._disPic();
									}, 3000);
								}
							},
							_getDisArr : function(){
								var arr = [],
									arr0 = [],
									arr1 = [],
									list = this.list;
								for(var i in list){
									if(list[i] && list[i][0] && list[i].length>0 ){
										arr.push(+i);
									}
								}
								for(var i = 0; i < arr.length; i++){
									for(var y = 0; y < list[arr[i]].length; y++){
										if(list[arr[i]][y].dis == 1){
											arr1.push([arr[i],y]);
										}else{
											arr0.push([arr[i],y]);
										}
										
									}
									
								}
								return [arr, arr0, arr1];
							},
							_disPic : function(){
								var arrAll = this._getDisArr(),
									arr = arrAll[0],
									arr0 = arrAll[1],
									arr1 = arrAll[2],
									list = this.list,
									_this = this,
									disObj;
																
								if(arr1.length){
									var r = this.createRanNum(1, 0, arr1.length-1)[0];
									list[arr1[r][0]][arr1[r][1]].dis = 0;
									$(list[arr1[r][0]][arr1[r][1]].marker.div_).find('.weibo-live').fadeOut('fast', function(){
										disObj = arr1.splice(r, 1);
										disHidePic(r);
									});
								}else{
									disHidePic();
								}			
								function disHidePic(r){
									//若存在arr1，则arr0与arr1取差
									if(r==0 || r) {
										for(var i = 0; i < arr1.length; i++){
											for(var y = 0; y < arr0.length; y++){
												if(arr1[i][0] == arr0[y][0]){
													arr0.splice(y,1);
													y--;
												}
											}
										}
									}
									var sign = arr0[0][0];
									var arr02 = [];
									for(var i = 0;i< arr0.length; i++){
										if(arr0[i]){
											if(!(sign == arr0[i][0])){
												sign = arr0[i][0];
											}											
												if(arr02[sign] && arr02[sign].length>=1){
													arr02[sign].push(arr0[i][1]);
												}else{
													arr02[sign] = [];
													arr02[sign].push(arr0[i][1]);
												}
										}																					
									}
									
									
									for(var i = 0;i< arr02.length; i++){
										if(arr02[i]!=undefined){
											var r2 = _this.createRanNum(1, 0, arr02[i].length-1)[0];
											list[i][arr02[i][r2]].dis = 1;
											var lives = $(list[i][arr02[i][r2]].marker.div_).find('.weibo-live');
											lives.fadeIn();
										}
									}	
								}	
							},
							_getDirection : function(num){
								//返回数组：大图向左[1,0]，小图向右[0,1]								
								switch (num) {
									case 0:
										return [1,0];
										break;									
									case 1:
										return [1,0];
										break;									
									case 2:
										return [0,1];
										break;									
									case 3:
										return [1,1];
										break;									
									case 4:
										return [0,0];
										break;									
									case 5:
										return [1,1];
										break;									
									case 6:
										return [0,0,35];
										break;									
									case 7:
										return [0,0,-20];
										break;									
									case 8:
										return [0,1];
										break;									
									case 9:
										return [0,1];
										break;									
									case 10:
										return [0,1];
										break;									
								}
							},
							formatWb : function (){
								var list = this.list;									
								for(var i in this.area){
									for(var y in this.area[i]){
										for(var z in this.temp){
											if(this.area[i][y] == z){
												for(var x in this.temp[z]){
													this.temp[z][x].dis = 0;
													this.temp[z][x].marker = X.use('CustomMarker', {
														map : this.map,
														data : this.temp[z][x],
														direction : this._getDirection(i-1)
													});
												}
												if(!list[i-1]){
													list[i-1] = [];
												}
												list[i-1] = list[i-1].concat(this.temp[z]); 
											}
										}
									}
								}
								this.temp = null;
								
							},
							getData : function(num){
								var ret = [],
									fCount = 0,
									temp = this.temp,
									_this = this;
								Req.getWbBySpotId(this.getIds(num), function(e){
									if(e.isOk()){
										var data = e.getData();
										_this.temp = data;
										_this.tempReady = 1;
									}
									setTimeout(function(){ _this.getData(5) }, 60000);
								})
								
							},
							deleteData : function(num){
								var count = this.getCount();
								var arr = [];
								var list = this.list;
								if(count > num){
									for(var i in list){
										if(list[i] && list[i].length > 4){
											for(var y = 0; y < list[i].length; y++){
												if(list[i][y].dis == 0){
													list[i][y].marker.setMap(null);
													list[i].splice(y,1);
													count--;
													if(count <= num){
														return true;
													} 
												}
											}										
										}																				
									}								
								}
							},
							getCount : function(){
								var count = 0;
								for(var i in this.list){
									count += this.list[i].length;
								}
								return count;
							},
							getIds : function(num){
								var arr = [],
									ret = [];
								for(var i in this.area){
									for(var y in this.area[i]){
										arr.push(this.area[i][y]);
									}
								}
								var ids = this.createRanNum(num, 0, arr.length);
								for(var i = 0; i < ids.length; i++){
									ret.push(arr[ids[i]]);
								}
								return ret.join(',');
							},
							createRanNum : function(num, min, max){
								var range = max - min;
								if (range == 0) { return [0,0]; }
								if (num > range) { return false; }								
								var ramNum = [];
								ramNum.push(Math.round(Math.random()*range));
								for(var y=0; ; y++){
									ramNum.push(Math.round(Math.random()*range));
									for(var i=0; i < ramNum.length-1; i++){
										if(ramNum[i]==ramNum[ramNum.length-1]){
											ramNum.pop();
											break;
										}
									}
									if(ramNum.length >= num){
										for(var i=0; i < num; i++){
											ramNum[i] = ramNum[i] + min;
										}
										return ramNum;
									}
									
								}
							} 
							
						}
						window.map1 = X.use('weiboLive', {
							mapId : 'googlemap',
							mapCfg : {
								center: new google.maps.LatLng(38.134557,106.86035),
								zoom: 4,
								mapTypeId: google.maps.MapTypeId.ROADMAP,
								disableDoubleClickZoom : true,
								draggable : false,
								disableDefaultUI : true,
								scrollwheel : false, //滚轮缩放
								keyboardShortcuts : false //禁止键盘快捷键
							},
							data : cfg.data							
						})
												
					})				
				});				
			}				
		})
	

		//游记
		.reg('space.map', {
/*             ui : {
				rightLists : false, //右边列表
				canClick : false,
				canDrag : false,
				unToCenter: true,//不允许居中				
				hasNav : false,
				viewCtl : false,
                cls : X.mod.footMarkMine
            }, */
            
            onViewReady : function(cfg) {
                var ui = this.getUI(),
                    data = cfg.data,
                    foots = data.footmarks.footmarks
					newFootmark = data.lastest;
				
				//异步加载google map
				X.on('pipe.end', function(){					
					X.use('LoadGoogleMap').initUI({
							view:ui.getView(),
							rightLists : false, //右边列表
							canClick : false,
							canDrag : false,
							unToCenter: true,//不允许居中				
							hasNav : false,
							viewCtl : false
						}, this, foots);
				});	
				
				
                ui.getView();

                //ui.initFoots(foots);
				
				ui.jq('#have_been').text(data.userinfo.have_been);
				ui.jq('#want_go').text(data.userinfo.want_go)
                
            }
        })

		.reg('youji.homeBox',{
            cols : [],
			pageSize : 20,
			yjCount : 0,
			
            onViewReady : function(cfg){
				// "page" : 1,
				// "type" : 1,
				// "youjis_html"
				// "max_id" : "282",
				// "total_number" : 4
                var ui = this.getUI(),
                    data = cfg.data;
				$.extend(this,  data);

				var youjis_html =  this.youjis_html;
				this.yjCount = youjis_html.length;
				this.hasNextPage = true;  //第一次加载

                var loading = this.loading = ui.jq('#sloading');
                var cols = this.cols = [
                    ui.jq('#col_1'),
                    ui.jq('#col_2'),
                    ui.jq('#col_3')
                ];
				this.colCount = 3;
				ui.jq().delegate(".cont", "hover", function(){
					$(this).find('i').toggleClass("hidden");
				});

				if( this.yjCount.length !== 0){
					loading.cssDisplay(0);
				    this.createItems( youjis_html, Util.getBind(this, 'toLoadedSeq'));
				}
                else{
					loading.after('<div align="center">没有数据</div>');
					loading.cssDisplay(0);
				}
            },
			/**
            * @param {Array} HTML结构
            * @param [loadFn] 加载完成后
            */
            createItems : function( htmls, loadFn ){
                $.each(htmls, function(i, html){
                    var item = X.use('youjiItem', {
                        html: html,
                        onload : function(succ, view ){
                            loadFn && loadFn( view );
                        }
                    });
                });
            },
			//等待wb里的图片加载完后，逐个插入到页面
			loadedWbSeq : [],
			loadedCount : 0,
			toLoadedSeq : function( wb ){
				var $img = wb.find('p.pic img'), imgh = 0;
				if( $img[0] ){
					imgh = $img[0].height;  //img自身高度
				}
				wb.calcH = imgh;
				wb.calcH += 18 * Math.floor( wb.find('p.desc').html().length/21 ); //文本高度
				this.binaryInsert( this.loadedWbSeq, 0, this.loadedWbSeq.length-1, wb );
				
				var self = this;
				if( ++this.loadedCount < 4 )
					setTimeout( function(){ self.insertWbToPage(); },800); //头4个延迟800ms
				else self.insertWbToPage(); 
			},
			binaryInsert : function( wbArr, l, r, wb ){  //二分插入 
			    if( l === r || r <= 0){
				    if( wbArr.length !== 0 ) 
						wb.calcH < wbArr[l].calcH ? wbArr.splice(l,0,wb) : wbArr.splice(l+1,0,wb);
				    else 
					    wbArr.push( wb );
					return ;
				}
				var mid = Math.floor( (l + r)/2 );
				if( wb.calcH < wbArr[mid].calcH ){
				    this.binaryInsert( wbArr, l, mid-1, wb );
				}
				else if ( wb.calcH > wbArr[mid].calcH ){
				    this.binaryInsert( wbArr, mid+1, r, wb );
				}
				else {
				    wbArr.splice(mid, 0, wb);
				}
			},
			insertWbToPage : function(){
				var cols = this.cols,
				    tarCol = 0;
				for(var i = 1; i<this.colCount; i++){
				    if( cols[tarCol].height() > cols[i].height() )
						tarCol = i;    //取最小的列
				}
				var wb = this.loadedWbSeq.pop();
				wb.css('opacity',0);
				this.cols[ tarCol ].append(wb);  //取最后一个
				wb.animate({'opacity': 1},600, function(){
					$(this).removeAttr('style');
				});
				if(  --this.yjCount === 0 && this.hasNextPage ){
				    this.loadedCount = 0;
					this.hideLoading();
					this.adjust();
					this.enScroll = true;
					this.setScrollLoad();
				}
			},
			adjust : function(){
			},
			enScroll : false,
			times : 1000,   //可滚动次数
			setScrollLoad : function(){
			    var self = this;
			 	$(window).bind('scroll',function(){
				    if( !self.enScroll || self.times <= 0 ) return ;
					if( $(document).scrollTop() + Util.getClientHeight() > $(document.body).height() - 50 ){
						self.enScroll = false;
						self.showLoading();
						Req.getHomeYouji(  {page: ++self.page, type: self.type, max_id: self.max_id  } , function(r){
							self.enScroll = true;
							self.hideLoading();
							if(r.isOk()){
								var data = r.getData();
								if(data.youjis_html.length == 0){
									self.hasNextPage = false;
									$(window).unbind('scroll');
									return;
								}
								$.extend(self, data);
								self.hasNextPage = data.youjis_html.length < self.pageSize ? false : true;							
								self.times--;
								self.createItems( data.youjis_html, Util.getBind( self, 'toLoadedSeq'));
							} else {
								self.hasNextPage = false;
								$(window).unbind('scroll');
							}
						});
					}
				});
			},
            showLoading : function() {
                this.loading.cssDisplay(1);                
            },
            hideLoading : function() {
                this.loading.cssDisplay(0);
            }
        })
		
		//他的足迹
		.reg('footmark.ta_map', {
            ui : {
				rightLists : false, //右边列表
				canClick : false,
				hasNav : false,
                cls : X.mod.footMarkMine
            },
            
            onViewReady : function(cfg) {			
				var record = $('#record');
                X.on('footmark.updateCounter', function(nums){
                    record.find('#wantToNum').text(nums[1]);
                    record.find('#haveBeenNum').text(nums[2]);
                });
			

                var ui = this.getUI(),
                    data = cfg.data,
                    foots = data.footmarks
					newFootmark = data.lastest;
									
				//异步加载google map
				X.on('pipe.end', function(){					
					X.use('LoadBaiduMap').initUI({
							view :ui.getView(),
							rightLists : false, //右边列表
							canClick : false,
							hasNav : false
						}, this, foots);
				});	

				
                ui.getView();

                //ui.initFoots(foots);
                
                if (newFootmark) {
				    var foot = ui.jq('.fp-info-inn'),
					    st = 0,
					    flag = true,
					    ul = $('<ul></ul>'),
					    offsetWidth = 0;
					    
				    foot.append(ul);
				    $.each(newFootmark,function(i){
					    this.state = this.state == 1 ? ' 想去' : '去过'; 
                        var spotUrl, r = this;
                        if(r.type == 2) {
                            spotUrl = Req.mkUrl('spots', 'citySpots', {pid: r.province_id, id: r.id,cid:r.city_id ,'_r':null});
                        } else{
                            spotUrl = Req.mkUrl('spots', '', {name: r.name, id: r.id, '_r':null});
                        }
					    var html=X.ax.Tpl.parse('fpInfoList',$.extend({},this,{url:Req.mkUrl('footmark','ta',{id:this.sina_uid}),spotsUrl:spotUrl}));
					    var li = $(html);
					    ul.append(li);
					    offsetWidth += li.outerWidth(true);
					    if(offsetWidth > 504){
						    li.remove();
						    ul = $('<ul></ul>');
						    foot.append(ul);
						    ul.append(li);
						    offsetWidth = li.outerWidth(true);
					    }
					    
				    });
				    
				    var scroll = function(){
					    if(flag) {
						    foot.animate({marginTop:-32},800,function(){
							    foot.css('marginTop','0px');
							    foot.find('ul:eq(0)').appendTo(this);
							    if(flag)
								    st = setTimeout(scroll,4000);
						    });
					    } else {
						    clearTimeout(st);
					    }					
				    }
				    scroll();
				    foot.hover(function(){
					    flag = false;
					    clearTimeout(st);
				    },function(){
					    flag = true;
					    st = setTimeout(scroll,4000);
					    
				    });
                }
            }
        })
		
        //我的足迹
        .reg('footmark.mine_map', {
            //ui : {
            //    cls : X.mod.footMarkMine
            //},
            
            onViewReady : function(cfg) {
				var record = $('#record');
                var ui = this.getUI(),
                    data = cfg.data,
                    foots = data.footmarks,
					newFootmark = data.lastest;   
					
				//异步加载google map
				X.on('pipe.end', function(){
					X.use('LoadBaiduMap').initUI({view:ui.getView()}, this, foots);
				});	
				X.on('footmark.updateCounter', function(nums){
					record.find('#wantToNum').text(nums[1]);
					record.find('#haveBeenNum').text(nums[2]);
					if(Number(nums[1])>=5 && Number(nums[2])>=5){
						ui.jq('#fpMedal').slideDown('slow',function(e){
							$(this).remove();
						})
					}
						
				});
				
                //ui.getView();
                //ui.initFoots(foots);
                if (newFootmark) {
				    var foot = ui.jq('.fp-info-inn'),
					    st = 0,
					    flag = true,
					    ul = $('<ul></ul>'),
					    offsetWidth = 0;
					    
				    foot.append(ul);
				    $.each(newFootmark,function(i){
					    this.state = this.state == 1 ? ' 想去' : '去过'; 
                        var spotUrl, r = this;
                        //if(r.type == 2) {
                        //    spotUrl = Req.mkUrl('spots', 'citySpots', {pid: r.province_id, id: r.id,cid:r.city_id ,'_r':null});
                        //} else{
                            spotUrl = Req.mkUrl('spots', 'detail', { id: r.spots_id, '_r':null});
                        //}
					    var html=X.ax.Tpl.parse('fpInfoList',$.extend({},this,{url:Req.mkUrl('space','ta',{id:r.user_id}),spotsUrl:spotUrl}));
					    var li = $(html);
					    ul.append(li);
					    offsetWidth += li.outerWidth(true);
					    if(offsetWidth > 504){
						    li.remove();
						    ul = $('<ul></ul>');
						    foot.append(ul);
						    ul.append(li);
						    offsetWidth = li.outerWidth(true);
					    }
					    
				    });
				    
				    var scroll = function(){
					    if(flag) {
						    foot.animate({marginTop:-32},800,function(){
							    foot.css('marginTop','0px');
							    foot.find('ul:eq(0)').appendTo(this);
							    if(flag)
								    st = setTimeout(scroll,4000);
						    });
					    } else {
						    clearTimeout(st);
					    }					
				    }
				    scroll();
				    foot.hover(function(){
					    flag = false;
					    clearTimeout(st);
				    },function(){
					    flag = true;
					    st = setTimeout(scroll,4000);
					    
				    });
                }
				
				$("#btnGetMedalInfo").click(function(){  //勋章查询
				    X.use('action').doAct( this );
				})
            }
        })
        
        .reg('app.addFootmark', {
            ui : {
                cls : X.mod.footMarkMine,
                
                focusCS : 'search-box-focus',
                
                limit : 8,
                
                viewCtl : false,
				
                onViewReady : function(){
					X.mod.footMarkMine.prototype.onViewReady.apply(this, arguments);
					X.on('app.changeFoots', Util.getBind(this, 'changeFoots'));
                    
                    var $return = this.$return = this.jq('#fp_info .return');
                
                    var inst = this;
                    $return.click(function(e){
                        inst.retMyMap();
                        X.fire('app.resetShareMyFootmark', '');
                        e.preventDefault(true);
                    })
                    
                    this.profile_image_url = this.jq('#fp_icon').find('img').attr('src');
				},
                
                $return : null,
                
                changeFoots : function(foots, user) {
                    this.removeAll();
                    this.initFoots(foots, false);
                    
                    if (true) {
                        this.changeMode(1);
                        this.jq('#fp_title').text(user.name + '的足迹');
                        this.jq('#fp_icon').find('img').attr('src', user.img);
                    }
                },
                
                //返回我的足迹
                retMyMap : function() {
                     this.restore();
                     this.changeMode(0);
                     this.jq('#fp_title').text('我的足迹');
                     this.jq('#fp_icon').find('img').attr('src', this.profile_image_url);
                },
                
                viewMode : 0,
                
                changeMode : function(m) {
                    if (m != this.viewMode) {
                        if (m === 1) {
                            this.jq('#search_panel').cssDisplay(0);
                            this.jq('#fp_map').css('margin-right', '0');
                            this.clickEnabled = this.updateOnIdle = false;
                            this.$return.cssDisplay(1);
                        } else {
                            this.jq('#search_panel').cssDisplay(1);
                            this.jq('#fp_map').css('margin-right', '220px');
                            this.clickEnabled = this.updateOnIdle = true;
                            this.$return.cssDisplay(0);
                        }
                        
                        google.maps.event.trigger(this.map, 'resize');
                        this.viewMode = m;
                    }
                }
            },
            
            onViewReady : function(cfg) {
                 var ui = this.getUI(),
                    data = cfg.data,
                    foots = data.footmark;
                
                ui.getView();
                ui.initFoots(foots);
				ui.footsInit = foots;
            }
        })
        
		.reg('user.footbar',{
			onViewReady:function(cfg){
				var ui = this.getUI(),
					FriendBox = ui.jq('#FriendBox'),
					isInBox = false,
					ANode = ui.jq('#showBox'),
					FriendUL = FriendBox.find('ul'),
					timer = 0,
					_showTimer = 0,
					marginTop = 0;
					
				ANode.hover(function(){
					FriendBox.cssDisplay(1);
					$(this).addClass('roll-btn-on');
					isInBox = false;
					clearTimeout(_showTimer);
				},function(){
					setTimeout(function(){
						if(!isInBox){
							FriendBox.cssDisplay(0);
							ANode.removeClass('roll-btn-on');
							clearTimeout(timer);
						}
					},150);
				});
				
				FriendBox.hover(function(){
					isInBox = true;
					clearTimeout(_showTimer);
				},function(){
					_showTimer = setTimeout(function(){
						FriendBox.cssDisplay(0);
						ANode.removeClass('roll-btn-on');
						clearTimeout(timer);
					},800);
				});
				
				FriendUL.find('li').hover(function(){$(this).addClass('current');},function(){$(this).removeClass('current')});

				FriendBox.find('.up,.down').each(function(){
					var isup = $(this).hasClass('up'),liLength = FriendUL.find('li').length;
					$(this).hover(function(){
						function next(){
							timer = setTimeout(function(){
								
								if(liLength*36 > 175 - marginTop) FriendBox.find('.up').addClass('up-hover');
								else FriendBox.find('.up').removeClass('up-hover');
								
								if(marginTop < 0)FriendBox.find('.down').addClass('down-hover');
								else FriendBox.find('.down').removeClass('down-hover');
								
								if(isup){ 
									if(liLength*36 > 175 - marginTop)
										marginTop = marginTop - 4;
								}
								else {
									if(marginTop < 0)
										marginTop = marginTop + 4;
								}
								FriendUL.css({'marginTop':marginTop+'px'});
								next();
							},50);
						}
						next();
					},function(){
						clearTimeout(timer);
					});
				});
				
				var flag = true,st =0 ,scroll = function(){
					if(flag) {
						ui.jq('#userList').animate({marginTop:-30},600,function(){
							ui.jq('#userList').css('marginTop','0px');
							ui.jq('#userList li:eq(0)').appendTo(this);
								st = setTimeout(scroll,2000);
						});
					} else {
						clearTimeout(st);
					}
					
				}
				scroll();
				ui.jq('#userList').hover(function(){
					flag = false;
					clearTimeout(st);
				},function(){
					flag = true;
					st = setTimeout(scroll,500);
				});
			}
		})
        
        .reg('footmark.ta', {
            ui : {
                cls : X.mod.footmap,
                
                //override
                checkPlaceState : function(spots_id) {
                    return this.myfoots && this.myfoots[spots_id] || 0;
                },
                
                //extend
                onViewReady : function(){
                    this.myfoots = {};
                },
                
                actionMgr : true,
                
                onactiontrig : function(e){
                  switch (e.data.e) {
                  case 'setspot':
                                    
                    var spots_id = e.get('id'),
                        old_state = this.checkPlaceState(spots_id),
                        new_state = e.get('nst'),
                        self = this,
                        spots = this.foots[spots_id];
						
                    var is_new = !old_state;
                    
                    if (old_state == new_state) return;
                    
                    self.myfoots[spots_id] = new_state;
                    
                     Req.setStateSpots(spots_id, new_state, function(ret){
                         if (ret.isOk()){
                            var msg, operText, goText = new_state == 1 ? '想去的': '去过的';
                            
                            operText = is_new ? '添加': '设置';
                            
                            msg = '成功'+operText+'<span>' + spots.name + '</span>为你' + goText;

                            self.showTips(msg);
							
                         }
                    });
                    e.preventDefault(false);
                  break;
                  }
                    
                },
                
                //override
                getMarkerInfoContent : function(spots){
                    var key = spots.spots_id;

                    if (!this._infoContents[key]) {
                        var checkStr = ' checked="true"', 
                            
                            state = this.checkPlaceState(key),
                            
                            KnV = Util.encodeKnV({
                                st : state,
                                id : key
                            }),
                            
                           radio_name = 'spotstate_' + key;
                        var img = '';
                        if (spots.thumbnail_data && spots.thumbnail_data.square_pic)
                            img = '<img src="'+  spots.thumbnail_data.square_pic +'" class="show">';
                            
                        this._infoContents[key] = $('<div class="fp-info-inner" style="height:85px;" rel="'+KnV+'"><h3>'+spots.name+'</h3>'+img+'<p><label><input rel="e:setspot,nst:1" type="radio" name="'+radio_name+'"'+(state == 1 ? checkStr:'')+'>我也想去</label></p><p><label><input rel="e:setspot,nst:2" type="radio" name="'+radio_name+'"'+(state == 2 ? checkStr:'')+'>我也去过</label></p></div>')[0];
                    }

                    return this._infoContents[key];
                }
            },
            
            onViewReady : function(cfg) {
                var data = cfg.data,
                    foots = data.footmark,
                    myfoots = data.myFootmark;
                    ui = this.getUI();

                if (foots) {
                    ui.initFoots(foots);
                }
                
                if (myfoots) {
                    ui.myfoots = myfoots;
                }
            }
        })
		.reg('footmark.mineHeader',{
			onViewReady:function(){
				var ui = this.getUI(),tmp,time = false;
                
                X.on('footmark.updateCounter', function(nums){
                    ui.jq('#wantToNum').text(nums[1]);
                    ui.jq('#haveBeenNum').text(nums[2]);
					if(!time){
						tmp = nums[2];
						time = true;
					}
                });
				X.on('footmark.updateCounter',function(nums){
					var i =  nums[2];
					if(i != tmp){
						tmp = i;
						switch(i){
							case 10:
							case 30:
							case 50:
								Req.q(Req.mkUrl('api/spots/action','getShareString'),{
									id:getCfg('uid'),
									type:'MeetCon',
									total:i
								},function(r){
									if(r.isOk()){
										Xwb.use('Box',{
											mask:true,
											closeable:true,
											appendTo:document.body,
											info : r.getData(),
											cs:'win-fb-tips win-fixed',
											contentHtml:'fbTips',
											onViewReady:function(){
												var self = this;
												this.jq('#ok').click(function(){
													X.use('action').doAct(ui.jq('#Xwbshare'),ui.jq());
													self.close();
													return false;
												});
											}										
										}).display(1);
									}
								})

								break;
						}
					}
				});
			}
		})
        .reg('footmark.taHeader', {
            onViewReady:function(){
                var ui = this.getUI();
                X.on('footmark.updateCounter', function(nums){
                    ui.jq('#wantToNum').text(nums[1]);
                    ui.jq('#haveBeenNum').text(nums[2]);
                });
            }
        })
		
		//大景点中的某个景点的用户足迹状态（去过？已去？）
		.reg('spots.detail_destination_getmark', {
            onViewReady : function( cfg ) {
			    var tthis = this,
					spotState = cfg.data.state,
					ui = tthis.getUI();
				if( spotState  == 1 ){   // 设置想去、去过按钮状态
				    ui.jq('#spotAction').html('<span class="btn-been-checked"><i class="ico-been-checked-s3">去过</i></span><a href="#" rel="e:setspot,ns:2" class="btn-wantto"><i class="ico-wantto-s3">想去</i></a>');
				}
				else if( spotState == 2) {
					ui.jq('#spotAction').html('<a href="#" rel="e:setspot,ns:1" class="btn-been"><i class="ico-been-s3">去过</i></a><span class="btn-wantto-checked"><i class="ico-wantto-checked-s3">想去</i></span>')
				}
				
				function showFloat(obj, state){
					var $e = $(obj), off = $e.offset(), left = off.left + 65 - 300;
					var w = $e.parent().data('w'), h = $e.parent().data('h'), data = null;
					if(state == 1){
						var view = $('#wantTo');
						if(h) h.display(0);
						if(view.length == 0) return;
						if(w){
							w.display(1);
							return;
						}
						data = 'w';
						
					}else{
						var view = $('#haveBeen');
						if(w) w.display(0);
						if(view.length == 0) return;
						if(h){
							h.display(1);
							return;
						}
						data = 'h';
					}
										
					var box = X.use('Box', {
						autoRender : true,
						cs : 'win-tips-s2',
						appendTo : document.body,
						contentHtml : view.html(),
						closeable : true,
						onViewReady : function(){
							this.jq().offset({left:left, top:off.top + 25});
							//this.jq('#cl').click(function(e){e.preventDefault(); box.display(0)});
							if(state == 1) { 
								var html = this.jq().find('.win-con-in').eq(1).html();
								this.jq().find('.win-con-in').eq(0).html(html);
							}
						}
					}).display(1);
					$e.parent().data(data, box);
					
				}

				 X.use('action').reg('setspot', function(e){   //想去、去过按钮事件
				    var spots_id = e.get('id'),
                    	state = e.get('ns');
						fid = e.get('f');
					e.lock(1);	
					if(state == 2)
						Req.addJourney('','','','','',spots_id, 0,'', 0, function(r){
							if(r.isOk()){
								showFloat(e.src, 2);
								$(e.src).prev('span').replaceWith('<a href="#" rel="e:setspot,ns:1" class="btn-been"><i class="ico-been-s3">去过</i></a>');
                                $(e.src).replaceWith('<span class="btn-wantto-checked"><i class="ico-wantto-checked-s3">想去</i></span>');
							}else{
								Box.alert('',ret.getMsg());
							}
							e.lock(0);
						})
					else
						Req.addWantTo(spots_id, function(r){	
							var opt = {"cid":getCfg('c_id'),"spots_id":spots_id,"random":Math.random(),"ver":getCfg('version'),"uid":getCfg('uid'),"xt":"show_exp"}
							X.report.report(opt);						
							if(r.isOk()){
								showFloat(e.src, 1);
								$(e.src).next('span').replaceWith('<a href="#" rel="e:setspot,ns:2" class="btn-wantto"><i class="ico-wantto-s3">想去</i></a>');
								$(e.src).replaceWith('<span class="btn-been-checked"><i class="ico-been-checked-s3">去过</i></span>');
							}else{
								Box.alert('',ret.getMsg());
							}
							e.lock(0);
						})						
				})
				
            }
        })
		//大景点详细页， 在路上微博列表
		.reg('spots.get_feed_list', {
		    onViewReady : function( cfg ) {
			    if( cfg.data.is_dest === 0 ) //如果是小景点,直接返回. 0 小景点, 1 目的地
				    return ;
				
			    var ui = this.getUI();
				var weiboLis = ui.jq('li'), 
				    len = weiboLis.length, 
					curRow = 0,
					rowCount = 3,   //每行显示个数
					switchCount = Math.ceil(len/3);   //切换次数
			    for(var i=rowCount; i<len; i++)
				    weiboLis[i].className = 'hidden';   //只显示第一行
				
				ui.jq("#btn-chWeibo").click(function(){
					for(var i=curRow*rowCount, max=Math.min( curRow*rowCount+3, len) ; i < max ; i++)
					    weiboLis[i].className = 'hidden';
					curRow = (curRow+1) % switchCount;
					for(i=curRow*rowCount, max=Math.min( curRow*rowCount+3, len) ; i < max ; i++)
					    weiboLis[i].className = '';
				})
			}
		})
		//大景点最新最热游记列表
		.reg('spots.youji_list_in_detail_destination', {
		    onViewReady : function(cfg){
			    var cfgdata = cfg.data, pageCom = null, ui = this.getUI(), type = 1, uid = getCfg('uid');
				var $listBox = $(ui.view),  
				    $list = $listBox.children('ul');
				$listBox.attr('id','travelNotesListBox'+type);
				if($('#tabBar').length) {
					X.use('SwitcherExt', {	
						items :[{id:'#travelNotesListBox0',type:'0'},{id:'#travelNotesListBox1',type:'1'}, {id:'#travelNotesListBox2', type:'2'}],
						actoinObj : 'tabBar',
						view : ui.view.parentNode,
						cur : type,
						setTab : function(o){
							var cs = o.parent(), p = o.parent().parent()
							, s = p.find('em').parent(), oldRel = s.attr('rel')
							, oparam = Util.parseKnV(oldRel), newRel = cs.find('a').attr('rel'), nparam = Util.parseKnV(newRel) ;
							s.replaceWith('<span><a href="#" rel="'+oldRel+'">'+s.text()+'</a></span>');		
							cs.replaceWith('<span rel="'+o.attr('rel')+'"   class="cur"><em>'+o.text()+'</em></span>');	
							return true;
						},
						
						getPart : function(data){
							this.getHotOrNewYouji( data.type );								
						},
						
						getHotOrNewYouji : function( type ){
						    var self = this, conBox = $('#travelNotesListBox ul');
							Req.getHotOrNewYouji( { 'id': cfgdata.id, 'type': type, page: 1}, function(r){
								if(r.isOk()){							
									var data = r.getData(), html = data.html;
									//过滤出实际需要的的内容		
									var cls = 'travel-notes-list';
 									if(data.yj_number === 0)
										var cls = 'tips-null-s2';										
									var box = $('<div id="travelNotesListBox'+type+'" class="'+cls+'">'+$(html).html()+'</div>').appendTo($listBox.parent());
									data.html = null; // 清空html
									if(uid)
										X.use('usersCard',{items:box.find('.user_card')});	
									if(Number(data.total_number)/data.count>1) createPageBar(type, data, box, $list );
								}
							})
						}
					}); 
				}
				function createPageBar( type, param, appendTo, conBox ){
					pageCom = X.use('Page',{
						total : Number(param.total_number) || 0,
						pageSize : param.count,
						curPage : 1,
						spotId : param.id,
						type : type,	
						id : 'page_'+type,
						appendTo : appendTo,				
						loadData : function( page, fn){
							var self = this;
							Req.getHotOrNewYouji( { 'id': this.spotId, 'page': page, 'type': this.type }, function(r){
								self.lock = false;
								if(r.isOk()){
									fn && fn();//修改分页符
								    var html = r.getData().html;
									//过滤出实际需要的的内容
									appendTo.find('ul:eq(0)').replaceWith($(html).html());																		
									X.use('SetScroll').init({toTop : $('#tabBar').offset().top - 45, starStep : 100});
									if(uid)
										X.use('usersCard',{items:appendTo.find('.user_card')});									
								}
							})
						}	
					});
				};
				if(Number(cfgdata.total_number)/cfgdata.count>1) createPageBar(type, cfgdata, $listBox, $list );  //初始化
			}
		})
		
		//小景点详细页
		.reg('spots.cover_info_small', {
            onViewReady : function( cfg ) {
				var ui = this.getUI(), $uf = ui.jq("#unfold"), $f = ui.jq("#fold"), $summary = ui.jq("#summary");
				var spotState = cfg.data.state;
				if( spotState  == 1 ){   // 设置想去、去过按钮状态
				    ui.jq('#spotAction').html('<span class="btn-been-checked"></span><a href="#" rel="e:setspot,ns:2" class="btn-wantto"></a>')
				}
				else if( spotState == 2) {
					ui.jq('#spotAction').html('<a href="#" rel="e:setspot,ns:1" class="btn-been"></a><span class="btn-wantto-checked"></span></a>')
				}
				var foldHeight = 154;  //折叠后的高度
				var lis = $summary.parent().find('li'),
					otherH = ( lis.length ?　lis.length - 1 : 0 ) * 22,
                    summaryH = $summary.height();
					
				if( otherH + summaryH <= foldHeight ){
					$uf.addClass("hidden");
				}else{
					$uf.click( function(){
						$summary.parent().css('height', 'auto');
						$uf.addClass("hidden");
						$f.removeClass("hidden");
					});
					$f.click( function(){
						$summary.parent().css('height', foldHeight);
						$f.addClass("hidden");
						$uf.removeClass("hidden");
					});
				}								
			}
		})
		
		
		//路书 固定边栏
		.reg('spots.common_dest_bread_menu',{
			onViewReady: function( cfg ){

				// jscrollPane 自定义滚动条
				var element = $('.scroll-pane');
				if( !element[0] )
				    return ;
				element.jScrollPane({height:500});
				api = element.data('jsp');
				
				//固定边栏
				var $aside = $("#aside"),
					$mainBox= $("#mainBox");
				if(!$mainBox[0]) 
				    return ;
				
				//锚点调整高度
				var adjustHeight = $.browser.msie ? ($.browser.version == '6.0' ? 0 : 60) : 50;
				
				X.on('pipe.end', function(){
					var $anchorTars = $('div.tit-s5, div.tit-s6', $('div.raider-cont')), 
						len = $anchorTars.length,
						$aside_anchors = $aside.find('.raider-nav a'),
						mainBoxOT = $mainBox.offset().top;
					
					for(var i=0; i<len; i++){
						$anchorTars[i].t = $anchorTars[i].offsetTop;
						$aside_anchors[i].t = $aside_anchors[i].offsetTop;
					}
					
					var srollTime = new Date().getTime(), 
						timespan =  ($.browser.msie && $.browser.version < 9) ? 400 : 150,
						curIndex = -1;
					$(window).bind('scroll', scrollCallBack );
					function  scrollCallBack(){
						var st = $(document).scrollTop();
						var nt = new Date().getTime();
						if( nt - srollTime < timespan ){  //避免频繁触发
							if( st + 45 <  mainBoxOT ) {
								$aside[0].className = 'aside';
							}
							hideMod_dl();
							return ;
						}
						srollTime = nt;
						
						function hideMod_dl( ){  //是否隐藏下载路书的div
							var ch = Util.getClientHeight();
							if( ch < 620 ){
								if( st + ch > $('body').height() - 80 )
									$aside.find('.mod-download').addClass('hidden');
								else $aside.find('.mod-download').removeClass('hidden');
							}
						}
						if( st + 45 >= mainBoxOT ){
							$aside.addClass('fixed');
							hideMod_dl();
						}
						else {
							$aside[0].style.cssText = "";
							$aside[0].className = 'aside';
						}
						
						if( $.browser.msie ){  //关闭IE下的效果
							return ;
						}
						
						//开头锚点，结束锚优化
						if( st < 100 ){ //当滚动高度小于100，第一个锚点高亮
							return asideScroll(0);
						}
						else if( $(document.body).height() - st - Util.getClientHeight() < 300   ){   //最后一个锚点
							return asideScroll(len-1);
						}
						//精确锚点
						var posIndex = -1,   
						    diff1, diff2;   
						for(var i=0; i<len; i++){
							diff2 = $anchorTars[i].t - st - adjustHeight;  //找到第一个大于st的锚
							if( diff2 > 0 ){
								posIndex  = i;
								break;
							}
						}
						if( posIndex > 0 ){
						    diff1 = st + adjustHeight - $anchorTars[posIndex-1].t;
							asideScroll( diff2 > diff1 ? posIndex-1 : posIndex);
						}else if( posIndex != -1 )
							asideScroll(posIndex);
					}
					
					//滚动条滚动到指定项
					function asideScroll( itemIndex ){
						if( curIndex === itemIndex )
							return ;

						var t = $aside_anchors[itemIndex].t;
						
						if( $aside_anchors[curIndex] )
							$aside_anchors[curIndex].className = '';
							
						curIndex = itemIndex;
						
						if( $aside_anchors[itemIndex] )
							$aside_anchors[itemIndex].className = 'current';

						api.scrollToY( t-60, false );
					}
					X.use('action').reg('g', function(e){
						location.hash = "#"+e.get('i');
						var st = $(document).scrollTop();

						$(document).scrollTop( st - adjustHeight );

						$aside.find('a.current').removeClass('current');
						e.src.className = 'current';
					})
				});
			}
		})

		
		.reg('youji.friend_side',{
			onViewReady:function(cfg){
				var ui = this.getUI(),
					up = ui.jq('span.up'),
					down = ui.jq('span.down'),
					tourList = ui.jq('div.tour-item'),
					userList = ui.jq('div.slider-inner ul li');
				ui.jq('.slider-inner').makeScroll({dir:'top',nextBtn:down,prevBtn:up,ct:'ul',moveScorll:true,pace:2,showState:true,ldisabledCs:'up-hover',rdisabledCs:'down-hover'});
				userList.each(function(i){
					$(this).click(function(){
						tourList.cssDisplay(0);
						$(tourList[i]).cssDisplay(1);
						userList.removeClass('active');
						$(this).addClass('active');
					});
				});
				userList.hover(function(){
					$(this).addClass('current');
				},function(){
					$(this).removeClass('current');
				});
				
			}
		})
		.reg('youji.header',{
			onViewReady:function(cfg){
				var ui = this.getUI();
				
				Xwb.cfg.view_type = cfg.data.view_type;
				Xwb.cfg.youji = cfg.data.youji;
				Xwb.cfg.youji.img_data = eval('('+Xwb.cfg.youji.img_data+')');

				X.on('api.likeSpots',function(data){
					var reqdata = data.reqCfg.data;
					if(X.getCfg('youji')){
						var youji = X.getCfg('youji');
						var elem = ui.jq('a[rel="e:like,t:2"]');
						elem.attr('class',youji.whether_liked ? 'tour-like-done' : 'tour-like');
						elem.find('em').html(youji.like_count);
					}
				});
											
				if(!X.getUid()){    //右上侧登录框
		    		$(window).bind('scroll',function(){
						var loginBox2 = X.use('loginBox2'),
                            st = $(document).scrollTop(),
						    loginBox1 = $("div.win-login");
						if(loginBox1[0] && loginBox1.cssDisplay()){   //如果另一个登录框已显示, 就不显示loginBox2
						    return ;
						}
						var ch = Util.getClientHeight();
                		if( loginBox2.scrollShow && ( st > ch || st + ch + 5 >= $('body').height() ) )
							loginBox2.graduallyShow(1);
						else if( st < 50 )
						    loginBox2.graduallyShow(0);
					});
				}
				X.cfg.args = cfg.data.args;
			}
		})
		.reg('spots.citySpots',{
			onViewReady:function(){
				var ui = this.getUI().jq(),height = ui.height();
				ui.find('span.up').click(function(){
					var sthis = $(this);
					if(sthis.hasClass('up')){
						sthis.attr('class','down');
						ui.animate({height:39});
					} else {
						sthis.attr('class','up');
						ui.animate({height:height});
					}
				})
			}
		})
		.reg('footmark.mine_no_login', {
			foots: null,
			
			onViewReady : function(cfg) {
				//初始化足迹数据
				this.foots = [];
				this.queue = [];

				var data = cfg.data,
				
					footmarks = data.newFootmark;

				var marks = this.push(footmarks);

				this.addQueue(marks);
				this.play();
			},

			queue : [],

			//播放窗口,正在显示的元素会放入这里
			container : [],

			//0 停止 1播放
			playStatus : 0,

			//开始播放效果
			
			play : function(elems) {
				this.show();
			},

			addQueue : function(elems) {
				var queue = this.queue;
				if (elems) queue.push.apply(queue, elems);
			},

			//maxshow : 4,
			

			delay: 2000,

			stay : 6000,

			show : function(){
				var elem = this.queue.shift();


				if (!elem) {
					//重新填充队列
					this.addQueue(this.foots);
					elem = this.queue.shift();
				}

				var $panel = this.getUI().jq();
				elem.getView();
				var $elem = elem.jq();

				$elem.hide();

				var container = this.container;
				/*
				if (container.length >= this.maxshow) {
					container.shift().jq().hide('normal');
				}
				*/

				$panel.append(elem.view);

				$elem
				.fadeIn()
				.delay(this.stay)
				.fadeOut(function(){
					$(this).remove();
				});

				window.setTimeout(Util.getBind(this, 'show'), this.delay);
			},

			create : function(data) {
				data.profile_url = '';
				data.stateText = '想去';
				data.style = 'bubble-s' + (parseInt(Math.random()*100)%4+1);
				data.hidden = false;
				data.view = 'floatFootmark';
				var ele = X.use('base', $.extend(data, {
					onViewReady : function() {
						//console.log(this.lat, this.lng);
						var lat = this.lat,
							lng = this.lng;

						var sclaeX = ((129.699781 - 79.162672)*3600)/390,
							sclaeY = ((51.801957 - 20.416923)*3600)/280;

						var x = lng * 3600 / sclaeX,
							y = lat * 3600 / sclaeY;

						//console.log(x, y);

						this.jq().css({left: x - 463, top: 490-y});

					}
				}));

				return ele;
			},

			//增加足迹数据
			//data {array}
			push : function(data) {
				var marks = [];

				for (var i = 0, l = data.length; i < l; i++){
					marks.push(this.create(data[i]));
				}

				var foots = this.foots;
				foots.push.apply(foots, marks);
				
				return marks;
			}
		})
		.reg('user.feedBack',{
			onViewReady:function(){
				X.use('feeback',{
					view:this.getUI().jq('#feebackBox')[0]
				}).getView();
			}
		})
		
		.reg('spots.hotSpots',{
			onViewReady:function(){
				var ui = this.getUI(),placeList = ui.jq('ul.place-list'),page=1,lock = false;
				ui.jq('#change').click(function(){
					if(lock) return false;
					lock = true;
					var load = $(Xwb.ax.Tpl.parse('Loading'));
					placeList.html('');
					placeList.before(load);
					Req.q(Req.mkUrl('app','hotSpots'),{page:page+1},function(r){
						if(r.isOk()){
							var html='',data = r.getData();
							page = +data.page;
							$(data.list).each(function(){
								html += ['<li>',
										'	<a href="'+Req.mkUrl('spots','',{name:this.name,id:this.id})+'" target="_blank" class="pic"><img src="'+ (eval('('+this.thumbnail_data+');')).thumbnail_pic +'"></a>',
										'	<span><a href="'+Req.mkUrl('spots','',{name:this.name,id:this.id})+'" target="_blank">'+this.name+'</a></span>',
										'</li>'].join('');
							});
							placeList.html(html);
						}
						load.remove();
						lock = false;
					});
					return false;
				});
			}
		})
		
        .reg('app.inviteFriends',{
			onViewReady:function(){
				var ui = this.getUI(),placeList = ui.jq('ul'),page=1,lock = false;
				ui.jq('#change').click(function(){
					if(lock) return false;
					lock = true;
					var load = $(Xwb.ax.Tpl.parse('Loading'));
					placeList.html('');
					placeList.before(load);
					Req.q(Req.mkUrl('app','inviteFriends'),{page:page+1},function(r){
						if(r.isOk()){
							var html='',data = r.getData();
							page = +data.page;
							$(data.list).each(function(){
								html += ['<li>',
	    				    			this.invited ? '<span class="invited">已邀请</span>' : '<a rel="e:sd,type:appInvite,st:邀请好友,t:邀请好友,uid:'+ this.id +',n:'+this.name+'" class="invite" href="#"><span>+</span>邀请</a>',
	    				    			'<a class="user-pic" target="_blank" href="http://weibo.com/'+this.id+'"><img src="'+this.profile_image_url+'"></a>',
										'	<span class="user-name"><a target="_blank" href="http://weibo.com/'+this.id+'">'+this.name+'</a></span>',
										'</li>'].join('');
							});
							placeList.html(html);
						}
						load.remove();
						lock = false;
					});
					return false;
				});
			}
		})
        
		.reg('app.shareMyFootmark', {
            ui : {
                cache : null,
                
                //异步查询对象
                xhr: null,
                
                innerViewReady : function(){
                    this.cache = {};
                },
                
                //请求服务器，对象用户
                req : function(uid, info){
                    return Req.compare(uid, Util.getBind(this, 'reqCompleted'), {info: info})
                },
                
                reqCompleted : function(ret){
                    if (ret.isOk()) {
                       var cfg = ret.getRequestCfg(),
					   	sina_uid = cfg.data.sina_uid,
						data = ret.getData(),
						info = cfg.info;

						data.user = info;

						this.cache[sina_uid] = data;

						this.showResult(data);
                    }
                    
                    this.xhr = null;

                },
                
                compare : function(uid, info){
                    this.xhr && this.xhr.abort();
                    
                    var cache = this.cache[uid];
                    
                    if (cache) {
                        this.showResult(cache);
                    } else {
                        this.xhr = this.req(uid, info);
                    }
                },
                
                //还原成自己的足迹状态
                reset : function(){
                    this.jq('#fp_cmp').cssDisplay(0);
                    this.jq('#fp_mine').cssDisplay(1);
                },

				showResult : function(data){
					var common = data.commonCount,
						my = data.count.my,
						ta = data.count.ta,
						user = data.user,
						myInfo = this.user;
                        
                    var fate = data.fate || 1;
                    
                    var txt;
                    
                    switch (fate) {
                    case 1:
                        txt = '缘分指数过低，分享并通知他你的想去成为有缘人';
                        break;
                    case 2:
                        txt = '缘分指数较低，分享并通知他你的想去成为有缘人';
                        break;
                    case 3:
                        txt = '你们的缘分指数已经超过<strong>50%</strong>的人，马上分享并通知他';
                        break;
                    case 4:
                        txt = '你们的缘分指数已经超过了<strong>80%</strong>的人，马上分享并通知他';
                        break;
                    case 5:
                        txt = '你们是旅游达人，马上分享并通知他下次一起旅行';
                        break;
                    }

					var opt = {
						f_profile_url : '#',
						f_profile_image_url : user.img,
						profile_url : '#',
						profile_image_url : myInfo.profile_image_url,
						f_wantTo : ta.want,
						f_haveBeen : ta.been,
						wantTo : my.want,
						haveBeen : my.been,
						commonHaveBeen : common.been,
						commonWantTo : common.want,
						fate : fate,
                        text : txt,
						fateMsg : data.fateMsg.replace(/:/g,'\\:')
					}

					var T = X.ax.Tpl,
						html = T.parse('UserCompare', opt);

					X.fire('app.changeFoots', data.footmark, user);

					this.jq('#fp_mine').cssDisplay(0);

					this.jq('#fp_cmp')
					.html(html)
					.cssDisplay(1);
				}
            },
            
            onViewReady : function(cfg){
				var ui = this.getUI();
				ui.user = cfg.data;
                X.on('app.compare', Util.getBind(ui, 'compare'));
                X.on('app.resetShareMyFootmark', Util.getBind(ui, 'reset'));
                
                X.on('footmark.updateCounter', function(nums){
                    ui.jq('#wantToNum').text(nums[1]);
                    ui.jq('#haveBeenNum').text(nums[2]);
                });
            }
        })
        
        //站内应用，比一比的好友
        .reg('user.topFriendsList', {
            ui: {
                actionMgr : true,
                onactiontrig : function(e) {
                    var data = e.data;
                    switch (e.data.e) {
                    case 'cmp':
                        X.fire('app.compare', data.id, {
                            sina_uid : data.id,
                            img : $(e.src).find('img').attr('src'),
                            name : data.n
                        });
                    break;
                    }
                }
            },
            onViewReady : function(cfg){
				var data = cfg.data;
				
				this.friends = data;

				var ui = this.getUI();
                ui.jq('div.bd').makeScroll({items:'li',dir:'left',nextBtn:'.arrow-r-s1',prevBtn:'.arrow-l-s1',ct:'ul',moveScorll:true,pace:2});
            }
        })
		.reg('spots.targetBanner',{
			ui:{
				actionMgr:true,
				onactiontrig:function(e){
					switch(e.get('e')){
						case 'setspot':
								var spots_id = parseInt(e.get('s'));
								var new_state = e.get('ns');
								var self = this;
								e.lock(1);
								 Req.setStateSpots(spots_id, new_state, function(ret){
									 if (ret.isOk()){
										if(new_state == '2'){
											self.jq('.btn-been-checked').replaceWith('<a href="#" class="btn-been" rel="e:setspot,ns:1"></a>');
											$(e.src).replaceWith('<span class="btn-wantto-checked"></span>');
											X.use('Tip',{
												view:$('#Xwb_been')[0],
												hidden:true,
												closeable:true,
												contextable:true,
												stayHover:true,
												timeoutHide:2000,
												beforeShow:function(){
													this.jq().stop();
													$('#Xwb_wantto').cssDisplay(0);
													var t = self.jq('.btn-wantto-checked')
														,offset = t.offset()
														,props = {left:offset.left,opacity:1}
														,self1 = this;
													props.top = t.outerHeight(1) + offset.top;
													this.jq().css($.extend(offset,{opacity:0}))
															.animate(props,'easeOut',function(){
																self1.hidden = false;
																self1.setContexted(true);
																self1.setHideTimer();
																e.lock(0);
															})
												}}).display(1);
										} else {
											self.jq('.btn-wantto-checked').replaceWith('<a href="#" class="btn-wantto" rel="e:setspot,ns:2"></a>');
											$(e.src).replaceWith('<span class="btn-been-checked"></span>');
											e.lock(1);
											if( $('#Xwb_wantto>div.avatars>a').length ){
												X.use('Tip',{
													view:$('#Xwb_wantto')[0],
													hidden:true,
													closeable:true,
													stayHover:true,
													timeoutHide:2000,
													beforeShow:function(){
														this.jq().stop();
														$('#Xwb_been').cssDisplay(0);
														var t = self.jq('.btn-been-checked')
															,offset = t.offset()
															,props = {left:offset.left,opacity:1}
															,self1 = this;
														props.top = t.outerHeight(1) + offset.top;
														this.jq().css($.extend(offset,{opacity:0}))
																.animate(props,'easeOut',function(){
																	self1.hidden = false;
																	self1.setContexted(true);
																	self1.setHideTimer();
																	e.lock(0);
																})
													}}).display(1);
											} else {
												e.lock(0);
											}
										}
									 }
								});
							break;
					}
				}
			},
			onViewReady:function(){
				var ui = this.getUI();
				ui.jq('#Xwb_been').appendTo(document.body).css({'z-index':10000});
				ui.jq('#Xwb_wantto').appendTo(document.body).css({'z-index':10000});
			}
		})
		.reg('spots.targetYouji',{
			lock : false,
			onViewReady:function(cfg){
				var self = this;
				this.cache = {
					New:{},
					Hot:{}
				};
				var ui = this.getUI();
				this.nowShow = ui.jq('.filter').find('a.curr').index() == 0 ? 'Hot' :'New';
				this.pageul = ui.jq('ul.page');
				this.pageLoading = ui.jq('#PageLoading');
				this.List = ui.jq('.travel-list');
				this.cache.New.total_page = this.cache.Hot.total_page = cfg.data.total_page;
				this.sid = cfg.data.sid;
				this.cache.Hot.nowPage = this.cache.New.nowPage = 1;
				this.updataPage();
				ui.jq('.filter').click(function(e){
					var txt = $(e.target).text();
					switch(txt){
						case '最新':
							self.nowShow = 'New';
							self.goPage(self.cache[self.nowShow].nowPage);
							$(this).find('a:eq(1)').addClass('curr');
							$(this).find('a:eq(0)').removeClass('curr');
							break;
						case '推荐':
							self.nowShow = 'Hot';
							self.goPage(self.cache[self.nowShow].nowPage);
							$(this).find('a:eq(0)').addClass('curr');
							$(this).find('a:eq(1)').removeClass('curr');
							break;
					}
					return false;
				});
				this.pageul.click(function(e){
					var sthis = $(e.target).parent();
					if(sthis[0].tagName == 'LI'){
						if(sthis.find('a').length){
							if(sthis.hasClass('next')){
								self.goPage(self.cache[self.nowShow].nowPage+1);
							} else	if(sthis.hasClass('prev')){
								self.goPage(self.cache[self.nowShow].nowPage-1);
							} else {
								self.goPage( +sthis.text() );
							}
						}
					}
					return false;
				});
			},
			updataPage:function(){
				var nowPage = this.cache[this.nowShow].nowPage,total_page = this.cache[this.nowShow].total_page;
				var splitPage = 3,html = '';
				if(nowPage == 1)
					html+='<span class="prev prev-disable">上一页</span>';
				else 
					html+='<span class="prev"><a href="#">上一页</a></span>';
					
				if(total_page > splitPage + 1){
					var min = nowPage - splitPage > 0 ? nowPage - splitPage : 1, max = min + splitPage*2 ;
					if(max > total_page){min -= max - total_page;max = total_page;}
					if(min != 1){
							html+='<a href="#">'+1+'</a>';
							min != 2 && (html+='<span>...</span>');
					}
					for(var i=min;i<=max;i++){
						if(i == nowPage){
							html+='<span>'+i+'</span>';
						} else {
							html+='<a href="#">'+i+'</a>';
						}
					}
					if(max != total_page){
							max != total_page - 1 && (html+='<span>...</span>');
							html+='<a href="#">'+total_page+'</a>';
					}
				} else {
					for(var i=1;i<=total_page;i++){
						if(i == nowPage){
							html+='<span>'+i+'</span>';
						} else {
							html+='<a href="#">'+i+'</a>';
						}
					}
				}
				
				if(nowPage == total_page)
					html+='<span class="next next-disable">下一页</span>';
				else 
					html+='<span class="next"><a href="#">下一页</a></span>';
				this.pageul.html(html);
			},
			goPage:function(page){
				var self = this;
				this.pageLoading.cssDisplay(1);
				if(this.lock) return;
				this.lock = true;
				if( !self.cache[self.nowShow][page] ){
					Req.q(Req.mkUrl('api/youji','getYoujiBySpotsId'),{sid:this.sid,sort:this.nowShow.toLocaleLowerCase(),page:page},function(r){
						if(r.isOk()){
							var html = '',data = r.getData().data;
							for(var key in data){
								var tmp = data[key];
								if( !tmp.youji_id ) continue;
								tmp.cover_img = $.parseJSON( tmp.cover_img.replace(/\\\"/g,'\"') );
								tmp.thumbnail_pic = tmp.cover_img.thumbnail_pic_1 ? tmp.cover_img.thumbnail_pic_1 : tmp.cover_img.thumbnail_pic;
								var date = new Date(+tmp.date * 1000)
								tmp.sortTime = date.getFullYear() + '-'  + (date.getMonth()+1) + '-' +date.getDate();
								tmp.likeCss = tmp.whether_liked ? 'ico-liked' : 'ico-like';
								tmp.like_count = tmp.like_count ? tmp.like_count : 0;
								tmp.comments_count = tmp.comments_count ? tmp.comments_count : 0;
								html += Xwb.ax.Tpl.parse('spotsYoujiList',tmp);
							}
							self.cache[self.nowShow][page] = html;
							self.cache[self.nowShow].nowPage = page;
							self.updataList(html);
						} else {
							//..
						}
					})
				} else {
					self.cache[self.nowShow].nowPage = page;
					self.updataList(self.cache[self.nowShow][page]);
				}
			},
			updataList:function(html){
				this.List.find('.travel-item').remove();
				this.List.find('.pagination ').before($(html))
				this.pageLoading.cssDisplay(0);
				$('html,body').animate({ scrollTop : this.List.offset().top - 60},'easeOut');
				this.lock  = false;
				this.updataPage();
			}
		})
		.reg('spots.targetOnTour',{
			onViewReady:function(){
				var ui = this.getUI(),list = ui.jq('ul li');
				ui.jq('#change').click(function(){
					var r = [],selectList=[];
					list.cssDisplay(0);
					for(var i=1;r.length != 3 && list.length > 3;i++){
						var t = parseInt(Math.random() * list.length);
						if($.inArray(t,r) !=-1 ) continue;
						r.push(t);
						selectList.push(list[t]);
					}
					$(selectList).cssDisplay(1);
					return false;
				});
			}
		})
		.reg('spots.footmarkCommon',{
			onViewReady:function(){
				var ui = this.getUI().jq();
				ui.click(function(e){
					if( $.inArray($(e.target).attr('class'),['arrow-up','arrow-down']) == -1 ){
						return;
					} else {
						var showLi = ui.parent().find('li span.arrow-up').closest('li')
							,self = this;
						if(showLi[0] == this){
							return false;
						} else {
							showLi.find('.avatars')
								.animate({height:0},function(){
									$(this).addClass('hidden')
										.css('height','');
										
									showLi.find('.arrow-up')
										.attr('class','arrow-down');
								});
							
							var avatars = $(this).find('.avatars'),
								h = avatars.find('a').length > 7 ? 72 : 39;
							$(this).find('.avatars')
								.height(0)
								.removeClass('hidden')
								.animate({height:h},function(){
									$(self)
										.find('.arrow-down')
										.attr('class','arrow-up');
								});
						}
					}
				});
			}
		})
		.reg('spots.filterSpots',{
		    onViewReady : function( cfg ){
			    //大分类选择
			    $("#bigPlaceList").delegate('a', 'click', function( e ){
				    var $this = $(this);
					var ftype = $this.parent().attr('data-rel'),
					    subType = encodeURI($this.attr('data-rel'));
					location.href = Req.mkUrl('spots','search') + '&' + ftype + '&' + subType;
					return false;
				});
				
				var ctf = $("#curFilterType").attr('data-rel');  //当前大分类的两个参数(字符窜)s
				//小分类过滤
				$("#placeFilter").delegate('a','click',function( e ){
				    var $this = $(this), $p = $this.parent();
					$p.children('a.cur').removeClass('cur');
					$this.addClass('cur');
                     
					var paramStr = ctf.split(',');
					$("#placeFilter a.cur").each( function( i, elm ){
					    var sp = elm.getAttribute('data-rel');
					    sp &&  paramStr.push( sp );
					});
					
					
					location.href = Req.mkUrl('spots','search') + '&' + Util.queryString(Util.dequery(paramStr.join('&')));
				    return false;
				});
			}
		})
		
		//新版
		.reg('consult.ask',{
			onViewReady : function(cfg){
				var ui = this.getUI(), f = ui.jq('#askForm'), info = ui.jq('#title,#content,#attractions')
				, selectLists = $('#selectLists'), selectUser = $('#userLists');
				
				//输入框提示
				X.use('InputLab',{items : info});
				
				//输入字数限制
				X.use('InputLimit',{items : [{obj:info[0],len:100},{obj:info[1],len:1500}]});
				
				//选择邀请用户
				selectUser.data('su',X.use('selectUser',{view : selectUser[0], 
				beforeCheck : function(e){
					return selectLists.data('sl').isFull();
				}
				,afterCheck : function(t, e){
					//选择后处理  
					selectLists.data('sl').dealBySu(t, e);
				}}));
				
				//取已邀请人数
				function getInvited(){
					return parseInt($('#invited').text());
				}
				
				var sl = X.use('base',{
					view : selectLists[0],
					autoRender : true,
					actionMgr : true,
					delUser : selectUser.del,
					onactiontrig : function(e) {
						switch (e.data.e) {
							case 'd':
								this.del(e);
							break;
						}
					},
					onViewReady : function(){
						
					},
					del : function(e){
						var id = e.get('u');
						selectUser.data('su').del(e);
						$(e.src).parent().remove();	
						this.reduce();
					},
					reduce : function(add){
						var inv = $('#invited'), n = parseInt(inv.text()), num = add?(n+1):(n-1);
						inv.text(num);
					},
					
					dealBySu : function(t, e){
						var u = e.get('u'), n = e.get('n');
						if(t){
							if(this.isSame(u)) return;
							this.add(u, n);						
						}else{
							this.jq('span[rel="u:'+e.get("u")+'"]').remove();
						}
					},
					
					isSame : function(u){
						return this.jq('span[rel="u:'+u+'"]').length;
					}
					,add : function(u,n){
						this.reduce(true);
						$('<span class="item" rel="u:'+u+'"><a rel="e:d" href="#">x</a>'+n+'</span>').insertBefore(selectLists.find('input'));
					},
					isFull : function(){
						return selectLists.find('span.item').length < 10
					}
				});
				
				selectLists.data('sl',sl);
				
				//添加景点
				var search = X.use('search', {
					inputor : $(info[2]),
					focusCS : '',
					view : info[2].parentNode,
					catchClick: true,
					onEnter : function(e, row){
						$(info[2]).val(row.name).attr({'rel':row.id,vrel:row.name});
					}
				});
				$(info[2]).blur(function(){
					var  $t = $(this);
					if($t.attr('vrel') != Util.trim(this.value)){
						$t.attr({'rel':'','vrel':''}).val('');
					} 
				})
				search.display(1);
				
				var autoInput = $('#autoInput').click(function(){
					this.value = '';
				});
				
				//显示更多
				$('#showMore').click(function(e){
					e.preventDefault();
					$('#userLists li:hidden').show();
					$(this).hide();
				});
				
				//增加邀请的人
				this.atWho = Xwb.use('atWho',{
					appendTo:document.body,
					Inputor : autoInput,
					autoRender : true,
					noAt:true,
					url : Req.jsAPI('userApi','at_user'),
					afterChoose:function(data){
						var lists = selectLists, id = data.user_id, name = data.nickname, sl = lists.data('sl');
						//先判断是否已选择
						if(sl.isSame(id) || !sl.isFull()){
							this.reset();
							return;
						}
						sl.add(id, name);	
						this.reset();
					},
					reset : function(){
						this.Inputor.val('').focus();
					}
				});
				
				//提交提问
				ui.jq('#askSubmit').click(function(e){
					e.preventDefault();
					var $t = $(this), info = ui.jq('#title,#content,#attractions');
					if($t.attr('lock')) return;
					var title = $(info[0]);
					if(title.val() == '' || title.val() == title.attr('lab')){
						Box.alert('','请输入问题',function(){
							title.focus();
						})
					}
					var attractions = $(info[2]);
					if(attractions.attr('rel') == ''){
						Box.alert('','请输入景点',function(){
							attractions.focus();
						})
					}
					
					
					//收集数据
					var con = $(info[1]).val() != $(info[1]).attr('lab') ? $(info[1]).val() : ''
					,span = selectLists.find('span'), uids = [];
					for(var i=0;i<span.length;i++){
						uids.push(Util.parseKnV(span.eq(i).attr('rel')).u);
					}
					
					Req.ask({title : title.val(),content : con, sid : attractions.attr('rel'), uids : uids.push(',')},function(e){					
						if(e.isOk()){
							Box.success('','问题添加成功');
						}else{
							Box.alert('',e.getMsg());
						}
					})
				})
				var p = X.use('Page',{getCount:function(){
					//异步取数据
					this.total = 100;
					this.start();
				}});
				//p.create();
			}
		})
		
		//问题详细页
		.reg('consult.doAnswer', {
			onViewReady : function(cfg){
				var param = Util.dequery(location.href);
				if(!X.getCfg('uid')){//处理登录框 
					X.use('action').reg('lg',function(e){
						e.evt.preventDefault();
						X.use('multiLogin', {
							iframeSrc: e.src.href,
							logTrue : function(){							
								this.close(true);
								location.href = mkUrl('consult','detail','id='+param.id+'#ans');
							}
						});
					}, {na: true});
					return 
				}else{
					$('#doAsk').click(function(e){
						e.preventDefault();
						var $t = $(this);
						if($t.data('lock')) return;
						var v = Util.trim($('#ask').val());
						if(v){
							Req.doAsk({content:v,qid:param.id},function(e){
								if(e.isOk()){
									$('#answerLists ul.list').append(e.getData());
									$('#ask').val('');
									$t.data('lock',0)
								}else{
									Box.alert('',e.getMsg());
								}
							});
						}
					})
				}
			}
		})
		
		//个人空间
		//个人足迹
		.reg('space.footmark_list', {
			onViewReady : function(cfg){
				var ui = this.getUI(), parent = $('#footmark'), d = cfg.data;
				parent.append(d.html);
				X.use('LoadPage', {parent:$('#footmark'), cfg : cfg}).getView();
			}
		})
		
		
		//我的游记
		.reg('space.youji_list' ,{
			onViewReady : function(cfg){
				var d = cfg.data, uid = d.uid, parent = $('#sortLists'), pageSize = Number(cfg.data.count)
				, type = d.type, types = ['ori','like','comments'], u = getCfg('uid');
				for(var i = 0 ;i<types.length;i++){
					if(types[i] == type){
						type = i;
						break;
					}
				}

				$(d.html).appendTo(parent).attr('id','sortList_'+type);

				function setupPage(param, fn){
					X.use('Page',{
						total : param.total,
						pageSize : pageSize,
						curPage : 1,
						appendTo : parent,				
						id : 'pagePart_'+param.type,
						loadData : function(page, fn){
							var self = this;
							Req.getYoujis({uid:uid, page: page, type:types[param.type]}, function(r){
								self.lock = false;
								if(r.isOk()){
									fn && fn();//修改分页符
									var d = r.getData(), id = 'sortList_'+param.type, $h = $(d.html);
									setTimeout(function(){
										parent.find('#'+id).replaceWith($h);										
										$h.attr('id',id);
										if(u)
											X.use('usersCard',{items:$h.find('.user_card')});	
										//setScroll(parent.offset().top);
										X.use('SetScroll').init({toTop : parent.offset().top - 45});
									},200);	
								}
							})
						}	
					});
				};
				if(Number(d.total)>pageSize)
					setupPage({total:d.total, type: type});
				
				if($('#sortLab').length)
					X.use('SwitcherExt', {					
						items :[{id:'sortList_0',type:'0'},{id:'sortList_1',type:'1'},{id:'sortList_2',type:'2'}],
						actoinObj : 'sortLab',
						setTab : function(o){
							var p = o.parent(), s = p.find('span'), oldRel = s.attr('rel'), oparam = Util.parseKnV(oldRel), newRel = o.attr('rel'), nparam = Util.parseKnV(newRel) ;
							s.replaceWith('<a href=# rel="'+oldRel+'">'+s.text()+'</a>');		
							parent.find('#pagePart_'+oparam.s).hide();
							parent.find('#sortList_'+oparam.s).hide();	
							o.replaceWith('<span rel="'+o.attr('rel')+'">'+o.text()+'<em></em></span>');	
							return true;
						},
						
						getPart : function(data){
							var sortLists = parent.find('#sortList_'+data.type);
							if(sortLists.length){
								sortLists.show();
								parent.find('#pagePart_'+data.type).show();
							}else
								Req.getYoujis({uid:uid, type:types[data.type], page: 1}, function(r){
									if(r.isOk()){							
										var rd = r.getData();
										parent.find('#sortLists>div:visible').hide();
										var $h = $(rd.html).appendTo(parent).attr('id','sortList_'+data.type);
										if(u)
											X.use('usersCard',{items:$h.find('.user_card')});
										if(Number(rd.total)>pageSize)
											setupPage({total:rd.total, type: data.type});
									}
							})
						}
					}); 
			}
		})

		//个人空间关注
		.reg('space.follower', {
			onViewReady : function(cfg){
				this.getUI().jq('ul.list>li').hover(function(e){
					var $t = $(this);
					if($t.find('a.ico-del-s2').length || $t.find('a.ico-each-followed').length){
						$t.find('a.ico-del-s2').cssDisplay(1);
						$t.find('a.sdm').cssDisplay(1);
					} 
				},function(e){
					var $t = $(this);
					$t.find('a.ico-del-s2').cssDisplay(0);
					$t.find('a.sdm').cssDisplay(0);
				});
			}
		})
		
		//个人空间粉丝页
		.reg('space.fans', {
			onViewReady : function(cfg){
				this.getUI().jq('ul.list>li').hover(function(e){
					var $t = $(this);
					if($t.find('a.ico-del-s2').length || $t.find('a.ico-each-followed').length){
						$t.find('a.ico-del-s2').cssDisplay(1);
						$t.find('a.sdm').cssDisplay(1);
					} 
				},function(e){
					var $t = $(this);
					$t.find('a.ico-del-s2').cssDisplay(0);
					$t.find('a.sdm').cssDisplay(0);
				});
			}
		})
		
		//通知
		.reg('center.getList', {
			onViewReady : function(cfg){
				this.getUI().jq('ul.list>li').hover(function(e){					
					$(this).addClass('hover').find('div.operate').cssDisplay(1);
				},function(e){
					$(this).removeClass('hover').find('div.operate').cssDisplay(0);
				});
				/*
				X.on('public.unread', function(e){
					if(e.isOk()){
						if(e.getData()['friFeed']>0)
							$('#friFeed').text('('+e.getData()['friFeed']+')');	
						else
							$('#friFeed').text('');	
					}					
				});*/
			}
		})
		
		//单用户短消息
		.reg('message.post', {
			onViewReady : function(cfg){
				var ui = this.getUI(), uid = '';
				Xwb.use('base',{
					actionMgr : true,
					view:$('#msgBox')[0],
					onViewReady:function(){
						this.jqExtra('word', 'warn', 'sender', 'content', 'warnPos', 'uid');
						this.selectionHolder = X.use('SelectionHolder', {elem:this.jqContent[0]});
						this.jqContent.keyup(Util.bind(this.checkText, this));
					},
					
					checkText : function(){
						var v = $.trim(this.jqContent.val()),
							left = Util.calWbText(v, 140);
						if(left>=0){
							this.jqWord.html( '您还可以输入'+left+'字' ).removeClass('tips-error');
						}else{
							this.jqWord.html( '已超出'+(-left)+'字' ).addClass('tips-error');
						}												
						return left>=0 && v;
					},
					
					onactiontrig : function( e ){
						switch(e.data.e){
							// 点击发送
							case 'sd' :
								uid = e.get('u');
								this.send();
							break;
/* 							case 'ic':
								 X.use('emotion')
								  .setSelectionHolder( this.selectionHolder , this.checkText, this)
								  .showAt(e.src);
							break; */
						}
					},
					
					reset : function(){
						this.jqContent.val('');
						this.checkText();
					},
					
					send : function(){
						if(!this.sending){
							var d = this.validate(), 
								fn = Util.getBind(this, 'onSendLoad'),
								sndBtn = this.jqSendBtn;
							if(d){
									Util.disable( sndBtn, true);
									Req.sendMessage(d.u, d.t, d.c, fn);
								}
							}
					},
					validate: function(){
						var text = this.checkText(); 
						if(text){
							return {u:uid,c:text};
						}else{
							var self = this;
							if(text === ''){
								Box.alert('', '请输入短消息内容',function(){
									self.jqContent.focus();
								});
							}
						}
					},
					onSendLoad : function( e ){
						if(e.isOk()){
							var ul = $('ul.list'), hasLi = ul.find('li').length;
							hasLi ? $(e.getData()).insertBefore(ul.find('li:eq(0)')) :
								ul.append($(e.getData()));
							this.reset();
						}else {
							Box.alert('', e.getMsg());
						}
						this.sending = false;
						Util.disable( this.jqSendBtn, false);
					}
				}).display(1);
			}
		})

		.reg('youji.contentBaiscStyle',{
			onViewReady:function(cfg){
				var vtype = getCfg('view_type');
				var ui = this.getUI();
				var $imgWraps = ui.jq('div.img-wrap'), ids = [];
				if( /simple|preview/ig.test(vtype) ){
					$imgWraps.each(function(){
						var $this = $(this);
			 			var _src = $(this).attr('src').replace(':','\\:'),
							sarr = _src.split('/'),
							img_id = sarr[sarr.length-1].split('_web_pic')[0];
						ids.push(img_id);
						//直接插入图片不进行懒加载
						var sw = $this.css('width'), sh = $this.css('height');
						if(/img.t.sinajs.cn/.test(_src))//表情直接显示
							$this.replaceWith('<img src="'+$this.attr("src")+'" alt="'+$this.attr("title")+'"  style="width:'+sw+'px;height:'+sh+'px">');
						else
							$this.append('<img rel="e:imgcm,url:'+_src+'" src="'+$this.attr("src")+'" alt="'+$this.attr("title")+'"  style="width:'+sw+'px;height:'+sh+'px">');		
					});
				}
				
				if(getCfg('view_type') == "simple" &&　ids.length){
					Req.jsApiCall('center','is_faved',{ ids: ids.join(',') }, function(rst){
						if( rst.isOk() ){
							var favedArr = rst.getData();
							for(var i=0;i<ids.length;i++){
								for(var j=0;j<favedArr.length;j++){
									if( ids[i] == favedArr[j] )   //已经添加过印象的图片
										$imgWraps.eq(i).data('isfaved',true);
								}
							}
							var yj_id = getCfg('youji').id;
							$imgWraps.each(function(i,item){
								var _src = ids[i];
								var url = $(this).attr('src').replace(':','\\:');
								
								
								$(this).append([
                                    '<div id="action_'+ids[i]+'" class="action hidden">',
									'<span class="btn-common">分享到<a title="分享到新浪微博" target="_blank" rel="e:share,t:1,na:1,imgurl:'+_src+',yjid:'+yj_id+',postType:yjsd" class="ico-sina-s1" href="#"></a><a  target="_blank"  rel="e:share,t:2,na:1,imgurl:'+_src+',yjid:'+yj_id+',postType:yjsd" title="分享到腾讯微博" class="ico-qq-s1" href="#"></a><a rel="e:share,t:3,na:1,imgurl:'+_src+',yjid:'+yj_id+',postType:yjsd"  target="_blank" title="分享到人人网" class="ico-rr-s1" href="#"></a></span>',
									($(this).data('isfaved') ? '<div class="btn-common">印象已添加</div>' : '<a rel="e:aim,imgurl:'+_src+',yjid:'+yj_id+'" class="btn-common" href="#">添加印象</a>'),
									'<a rel="e:imgcm,focus:1,url:'+url+'" class="btn-common" href="#">评论图片</a>',									
                                    //'<a rel="e:sd,u:'+yj_id+',t:yjsd,pic:'+url+'" class="btn-common" href="#">分享到微博</a>',
								'</div>'].join(''));
							});
						}
					},'POST');
					
					
					$imgWraps.hover(function(){
						if($(this).find('img').width()>100) //太小的图不加
							$(this).find('div.action').cssDisplay(1);
					},function(){
						$(this).find('div.action').cssDisplay(0);
					});
				}
				//X.use('lazyLoadPic');
			}
		})
		
		 // 具体微博页面
        .reg('spots.comment_box_in_weibo_detail', function(){
            return new WBPipe({
                onViewReady : function(v){
					var loadPic = $('#loadPic');
					if(loadPic.length){
						var src = loadPic.attr('_src');
						Util.drawImage(src, 669,3000,function(obj){
							loadPic.attr({height:obj.height,width:obj.width,src:src});
						})
					}
				
					var self = this;
					$('#weiboCmt').click(function(e){
						e.preventDefault();
						self.jq('#inputor').focus();
					});
					
					Req.getComments = function(id, page, type, fn, cfg){
						this.act('feedApi','comment_list', {fid:id, cursor:cmt.next_cursor || 0, type:type||1}, fn, cfg);
					}
					var ui = this.getUI();
					var cmt = X.use('CmtArea', {
                        wbId :  v.data.id,
                        wbUid :  v.data.uid || 1794880466,
                        appendTo: ui.jq(),
						getCommentUrl : Req.getComments,
						commentUrl : Req.comment,
						replyUrl : Req.reply,
						showEmotion : false,
						relaySystem : true,
						profileImg : getCfg('face_m') || '/img/default.png',
						next_cursor : 0,
                        trigEl : '#b_comment',
						share : '分享给我的粉丝',
						localComments : false,
                        createListUI : function(e){						
							this.jqCmtCt.empty();
							var listData = e.getData(), data = listData.data;
							this.next_cursor = listData.next_cursor;
							var lef = this.next_cursor >0 ? true : false;
							var htmls = [], self = this;
							
							for(var k in data){
								htmls[htmls.length] = this.createCmtUI(data[k]);
							}
							if(htmls.length){
								this.jqCmtCt.html( htmls.join('') );
								if( lef ){
									this.jqMore.cssDisplay(true);
									this.jqLefCnt.text(lef);
								}else this.jqMore.cssDisplay(false);
								this.jqCmtCt.cssDisplay(true);
							}else {
								this.jqCmtCt.cssDisplay(false);
								this.jqMore.cssDisplay(false);
							}
							if(getCfg('uid'))
								X.use('usersCard',{items:this.jqCmtCt.find('.user_card')});
							return htmls.length;
						},
						updateCmtPageUI : function(pageInfo){
							// 如果存在分页按钮
							if(this.jqPre.length){
								this.jqPre.cssDisplay(this.page > 1);
								// 第三页后显示首页按钮
								this.jqFirst.cssDisplay(this.page > 1);
								this.jqNext.cssDisplay(this.next_cursor != -1);
							}
						},
                        onViewReady : function() {
                            var focusCS = 'style-focus';
                            this.jq('textarea').bind({
                                focus: function(){
                                    $(this).addClass(focusCS)
                                },
                                blur : function(){
                                    $(this).removeClass(focusCS);
                                }
                            })
							
							var args = X.cfg.args;
							if(args && args.cid && args.nick)
								this.cmtBox.reply(args.cid, args.nick);
                        },
						afterShow : function() {
                            //检测url Hash ，如果是comment，则focus到输入框
                            if (location.hash == '#comment') {
								$(document).scrollTop(this.jq().offset().top-75);
                                this.jq('textarea').focus();
                            }
                        }
                    });
                    cmt.display(1);
                    cmt.load();
                    X.cfg.cmt = cmt;

                }
            });
        })
		
		//首页 列表
		.reg('common.youjiTabs', {
			onViewReady : function(cfg){
				var ui = this.getUI(), uid = getCfg('uid');
				X.use('action',{
					target : ui.jq()
				}).reg('tab',function(e){
					var tab = e.get('t'), $t = $(e.src);
					if($t.children().length == 0){
						var old = ui.jq('#filter').find('span');
						old.replaceWith('<a rel="'+old.attr("rel")+'" href="#">'+old.text()+'</a>');
						$t.replaceWith('<span rel="'+$t.attr("rel")+'">'+$t.text()+'<em></em></span>');
						if(tab == '1'){
							ui.jq('#youjiList2').cssDisplay(0);
							ui.jq('#youjiList1').cssDisplay(1);							
						}else{
							ui.jq('#youjiList1').cssDisplay(0);
							if(cfg.data.latest){
								var l = $(cfg.data.latest.html).insertBefore(ui.jq('#youjiList2').find('div:eq(0)'));
								cfg.data.latest.html = '';	
								if(uid)
									X.use('usersCard',{items:l.find('.user_card')});								
							}
							ui.jq('#youjiList2').cssDisplay(1);		
						}
					}
				});
				
				var hots = cfg.data.hots, hotHtml = ui.jq('#youjiList1'), filter = $('#filter');
				if(Number(hots.total)/hots.count >1)
					X.use('Page',{
						total : Number(hots.total),
						pageSize : hots.count,
						curPage : 1,
						appendTo : hotHtml,				
						id : 'pagePart_1',
						loadData : function(c, fn){
							var self = this;
							Req.getHotList({page:c, count:20}, function(r){
								self.lock = false;
								if(r.isOk()){
									fn && fn();//修改分页符
									var html = r.getData();
									setTimeout(function(){									
										hotHtml.find('ul.list').replaceWith(html.list);
										//hotHtml.css({ opacity: 0.01 }).animate( {'opacity': 1}, 1500)	
										X.use('SetScroll').init({starStep : 105, toTop : filter.offset().top - 45});
										if(uid)
											X.use('usersCard',{items:hotHtml.find('.user_card')});
									},100);	
								}
								
							})
						}	
					});
					
				
				var latest = cfg.data.latest, latestHtml = ui.jq('#youjiList2');
				if(Number(latest.total)/latest.count >1)
					X.use('Page',{
						total : Number(latest.total),
						pageSize : latest.count,
						curPage : 1,
						appendTo : latestHtml,				
						id : 'pagePart_2',
						loadData : function(c, fn){
							var self = this;
							Req.getNewList({page:c, count:20}, function(r){
								self.lock = false;
								if(r.isOk()){
									fn && fn();//修改分页符
									var html = r.getData();
									setTimeout(function(){
										latestHtml.find('ul.list').replaceWith(html.list);
										if(uid)
											X.use('usersCard',{items:latestHtml.find('.user_card')});
										X.use('SetScroll').init({starStep : 105, toTop : filter.offset().top - 45});
									})										
								}
							})
						}	
					});
			}
		})
		
		.reg('pagination.nav', {
			onViewReady : function(cfg){
				$('#youjiList>li').each(function(i){
					var $t = $(this);
					$t.mouseover(function(){
						$t.find('i.count').cssDisplay(1);
					}).mouseout(function(){
						$t.find('i.count').cssDisplay(0);
					});
				});
			
				$('#pagePart a').click(function(e){
					e.preventDefault();
					var url = this.href, t = $(this).closest('#pagePart').parent();
					Req.q(url,{},function(e){
						if(e.isOk()){
							t.replaceWith(e.getData());
						}
					},{
						method : 'GET'
					})
				});
			}
		})
		//广告位
		.reg('common.focus', {
			onViewReady : function(cfg){
				$('#slider').fader({
					Main:'#sliderUL',
					Control:'#sliderControl',
					ControlCss:'current',
					img:'img[_src]',
					callback:function(page){
							
					},
					runningFn : function(){
						$('#info div:visible').fadeOut(300,function(){
							$('#info>div').eq($('#sliderControl a.current').index()).show();
						})
					},
					split : 3000
				});
			}
		})
		
		//首页左则切换
		.reg('common.recommend', {
			onViewReady : function(cfg){
				var ui = this.getUI();
				var tli = ui.jq('#titleLabel>li'), cli = ui.jq('div.dest-list'), timer = null;
				cli.each(function(i){
					$(this).data('d',i);
				});
				function hide(index){
					tli.eq(index).removeClass('current');
					cli.eq(index).cssDisplay(0);
				}
				tli.mouseover(function(e){
					clearTimeout(timer);
					tli.removeClass('current');
					var $t = $(this), index = $t.index();
					$t.addClass('current');
					if(cli.eq(index).hasClass('hidden')){
						cli.addClass('hidden');
						cli.eq(index).cssDisplay(1);
					}
				}).mouseout(function(e){
					var $t = $(this), index = $t.index();
					timer = setTimeout(function(){hide(index)}, 30);
				});
				
				cli.mouseover(function(e){	
					clearTimeout(timer);
				}).mouseout(function(e){						
					var $t = $(this), index = $t.data('d');
					if(index == null) return;
					timer = setTimeout(function(){hide(index)}, 30);
				});
			}
		})
		.reg('common.footprintLogin',{
			onViewReady:function(){
				var ui = this.getUI().jq();
				ui.click(function(e){
					var cls = $(e.target).attr('class');
					if( $.inArray(cls, ['arrow-up','arrow-down']) == -1 ){
						return;
					} else {
						var showLi = ui.parent().find('li span.arrow-up').closest('li')
							,self = $(e.target).closest('li');
						if(showLi[0] == self){
							return false;
						} else {
							showLi.find('.avatars')
								.animate({height:0},function(){
									$(this).addClass('hidden')
										.css('height','');										
									showLi.find('.arrow-up')
										.attr('class','arrow-down');
								});
 							var avatars = $(self).find('.avatars'),
								up = $(self).find('.arrow-up'),
								down = $(self).find('.arrow-down'),								
								h = avatars.find('a').length,
								num = Math.ceil(h/6);
							h = (num>2?2:num)*36 || 36;
							if(up.length){
								avatars.removeClass('hidden')
									.animate({height:0},function(){
										up.removeClass('arrow-up').addClass('arrow-down');
									})
							}else{
								avatars.removeClass('hidden')
									.height(0)
									.animate({height:h},function(){
										down.removeClass('arrow-down').addClass('arrow-up');
									})
							}
						}
					}
				});
			}
		})
		//景点微博页面
		.reg('spots.youji_list_in_weibo',{
			onViewReady:function(){
				var ui = this.getUI();
				var scrollerBox = ui.jq();
				if(scrollerBox.length){
					
					scrollerBox.find('.scroller-view')
						.makeScroll({
								nextBtn:scrollerBox.find('.next')
								,prevBtn:scrollerBox.find('.prev')
								,ct:'ul'
								,items:'li'
								,moveScorll:true
								,pace:5
						});
						
					scrollerBox.find('li').each(function(){
						var ANode = $(this).children('a'),lock = false, _timer = 0,h = -150 ,t = 400 ;
						$(this).hover(function(){
							if(lock)return;
							lock = true;
							_timer = setTimeout(function(){
								ANode.animate({top:h},t,'easeIn');
							},200);
						},function(){
							if(!lock)return;
							clearTimeout(_timer);
							ANode.animate({top:0},t,'easeOut',function(){
								lock = false;
							});
						});
					});
				}
			}
		})
		
		//用户面板
		.reg('user.userShow', {
			onViewReady : function(cfg){
				var ui = this.getUI();
				ui.jq('#numBar').hover(function(e){
					ui.jq('#expTips').cssDisplay(1);
				},function(){
					ui.jq('#expTips').cssDisplay(0);
				});
			
			}
		})
		
		.reg('youji.basicStyleSide', {
			onViewReady : function(cfg){
				var ui = this.getUI(), album = ui.jq('#album');
				
				if(album.length && getCfg('userCfg').youji_album == 0){
					X.use('Box',{
								contentHtml : '<div><div class="pic"><img src="/img/pictorial.jpg" width="42" height="42" /></div>'+
												'<div class="info">'+
													'猛击这里就有酷炫模式哦！'+
												'</div></div>'
								,cs : 'win-tips-s3 win-tips-toggle'
								,appendTo : '#container'
								,closeable:true
								,boxOutterHtml : '<p class="arrow-s1"><i></i></p>'
								,destroy : function(){
									this.jq().remove();
									Req.setRemind('youji_album', 1 ,function(){});
								}
								,onViewReady : function(){
									var self = this;
									function setWin(){
										var offset = ui.jq('#album').offset();
										self.jq().offset({top:offset.top+26});
									}
									setWin();
									setTimeout(function(){self.jq().css('zIndex',10000)},1);
									
									$(window).resize(function() {
										setWin();
									});
								}
								,destroyOnClose:true
					}).display(1);
				}	
			
			
				var likeFix = this.getUI().jq('#likeFix'),
                    classFixed = 'like-list-fixed',
                    fixed = likeFix.hasClass( classFixed );
                    
                if(!likeFix.length){
                    return ;
				}
                
                var ftop = likeFix.offset().top;
                
				$(window).bind('scroll',function(){
						//var clientHei = $.browser.msie ? document.documentElement.clientHeight : document.body.clientHeight;
                        var st = $(document).scrollTop();
                		if( st > ftop ){
							!fixed && likeFix.addClass( classFixed );
                            fixed = true;
						}else{
							fixed && likeFix.removeClass( classFixed );
                            fixed = false;
						}
					});
			}
		})
		
		//用户勋章
		.reg('user.userMedal', {
			onViewReady : function(cfg){			
				X.use('MedalBox',{items:this.getUI().jq('#userMedal img')});			
			}
		})
		
		.reg('events\/invite.lottery',{
		    onViewReady : function( cfg ){
			    var swfobjnaem = 'LuckyDraw';  //flash对象名称
				function getFlasMovie(movieName) {
					if(navigator.appName.indexOf("Microsoft") != -1) {
						return window[movieName];
					} else {
						return document[movieName];
					}
				}
				var ui = this.getUI(),
				    $lottC = ui.jq("#lotteryCount"),
				    oriLottCount = $lottC.attr("initVal") || 0,
					$lottBtn = ui.jq("#lott"),
					lock = 0,            //锁定
					lottInfo = {},       //抽奖返回的结果集
					b = [3,7,4,2,5,0,1];  // 后台结果与奖盘对应表
					
					// 0:'下次努力'
					// 1:'限量公仔'
					// 2:'雨伞'
					// 3:'T恤'
					// 4:"微博纪念书签"
					// 5:'1000'
					// 6:'10000'
				
				//flash提供的接口方法				
				function start(){
					getFlasMovie('LuckyDraw').startRotation();
				}
				function stop(){
					getFlasMovie('LuckyDraw').stopRotation( b[lottInfo.result] );
				}
			   	window.lottery = function(){
					$lottC.val( lottInfo.odds );
					if( lottInfo.odds == 0 ){   //是否还有抽奖机会
						$("#drawDone").removeClass("hidden");
						$("p.des").addClass("hidden");
						$lottBtn.replaceWith('<span class="btn-drawed">马上抽奖</span>');
					}else {
					  	$lottBtn.html( "再抽一次" );
					}
					$lottC.html( lottInfo.odds );
					
					var giftName = lottInfo.result_text;
					if( lottInfo.result === 0 ){   //是否中奖
						$("#drawFault").removeClass("hidden");
						$("p.des").addClass("hidden");
					}else if( lottInfo.result === 5 || lottInfo.result === 6 ){
						Box.success('提示','恭喜你获得'+giftName+'，再接再厉哦，大奖等着你！');
					}
					else {
                        $("#drawFault").addClass("hidden");
						X.use('giftBox', { title: "恭喜你！获得<em>"+ giftName +"</em>礼品！", lottId: lottInfo.id } );
					}
					lock = 0;
				}
				//flash 加载完成 接口;
				window.isLotteryDone = function(){
					ui.jq("#lott").click( getLotteryResult );
				}
				//flash提供的接口方法 end  ---------------------------
				
                function getLotteryResult(){
					if( lock ) 
					    return false;
					lock = 1;
					start();
				    Req.getLotteryResult( function( e ){
					    if( e.isOk() ){
						    lottInfo = e.getData();
							setTimeout( function( ){  stop(); },  2000 );
						}else 
							Box.alert("提示",e.getMsg());
					});
					return false;
				}
				
				//medal
				$('#medal').click(function(){
					X.use('Dlg',{
						cs : 'win-fixed win-medal',
						appendTo : "body",
						dlgContentHtml : X.ax.Tpl.parse('staticMedal'),
						title: '一呼百应',
						closeable : true,
						destroyOnClose : true,
						onViewReady : function(){}
				   }).display(1);
				   return false;
			   })
			}
		})
		
		
		//搜索页
		//景点
		.reg('search.spots', {
			onViewReady : function(cfg){
				if(cfg.data && cfg.data.keyword)
					this.getUI().jq('li div.info').highlight(cfg.data.keyword);
			}
		})
		//游记
		.reg('search.youji', {
			onViewReady : function(cfg){
				if(cfg.data && cfg.data.keyword)
					this.getUI().jq('ul.list>li').highlight(cfg.data.keyword);
			}
		})		
		//所有页用户
		.reg('search.all_user', {
			onViewReady : function(cfg){
				if(cfg.data && cfg.data.keyword)
					this.getUI().jq('li div.info').highlight(cfg.data.keyword);
			}
		})
        
        //经验搜索
        .reg('search.all_exp', {
            onViewReady : function(cfg){
                this.getUI().jq('ul.list').highlight(cfg.data.keyword);
            }
        })
		
		//用户页
		.reg('search.user', {
			onViewReady : function(cfg){
				if(cfg.data && cfg.data.keyword)
					this.getUI().jq('li div.info').highlight(cfg.data.keyword);
			
				this.getUI().jq('ul.list>li').hover(function(e){
					var $t = $(this);
					if($t.find('a.ico-del-s2').length || $t.find('a.ico-each-followed').length){
						$t.find('a.ico-del-s2').cssDisplay(1);
						$t.find('a.sdm').cssDisplay(1);
					} 
				},function(e){
					var $t = $(this);
					$t.find('a.ico-del-s2').cssDisplay(0);
					$t.find('a.sdm').cssDisplay(0);
				});
			}
		})
		
		//专题页评论
		.reg('special/exchange.guestbook', {
			onViewReady : function(cfg){
					var pid = cfg.data.pid;
					var ui = this.getUI();
					var cmt = X.use('CmtArea', {
                        wbId :  pid,
                        wbUid :  pid,
                        appendTo: ui.jq(),
						getCommentUrl : Req.getSpecialComment,
						commentUrl : Req.specialComment,
						replyUrl : Req.specialComment,
						profileImg : getCfg('face_m') || '/img/default.png',
						next_cursor : 0,
                        trigEl : '#b_comment',
						showEmotion : false,
						special : true,
						newSystem : true,
						commentHtml : 'SpecialComment',
						localComments : false,
						createCmtUI : function(data, user){
							var T = X.ax.Tpl, data = $.extend(data,user);
							data.usrUrl = Req.mkUrl('space','ta',{id:data.uid});
							data.user_card = 'user_card';
							data.level = 'LV.'+data.level;
							data.content = Util.escapeHtml(data.content);
							return T.parse( this.commentHtml, data);							
						},
						afterSend : function(e){
							var data = e.getData();
							var user = data.user;
							var jq = $(this.createCmtUI(data, user));
							this.jqCmtCt.prepend( jq );
							this.jqCmtCt.cssDisplay(true);
							this.updateCmtCountUI(1, true);
							this.itemHover(jq);
							// 解析评论里的短链接
							X.mod.shortlink.render(jq, function(urlInfo, aHref){
								aHref.title = urlInfo && urlInfo.url || getText('无效链接');
							});
							if(getCfg('uid'))
								X.use('usersCard',{items:jq.find('.user_card')});
						},
                        createListUI : function(e){						
							this.jqCmtCt.empty();
							var listData = e.getData(), lists = listData.list, users = listData.users;
							this.next_cursor = listData.next_cursor;
							var htmls = [], self = this;
							for(var k = 0,j = lists.length;k<j;k++){
								htmls[htmls.length] = this.createCmtUI(lists[k], users[lists[k]['uid']]);
							}
							if(htmls.length){
								this.jqCmtCt.html( htmls.join('') );
								this.jqCmtCt.cssDisplay(true);
							}else {
								this.jqCmtCt.cssDisplay(false);
								//this.jqMore.cssDisplay(false);
							}
							if(getCfg('uid'))
								X.use('usersCard',{items:this.jqCmtCt.find('.user_card')});
							return htmls.length;
						},
						updateCmtPageUI : function(pageInfo){
							if(!this.pages){
								var self = this;
								this.pages = X.use('Page',{
											total : pageInfo.count,
											pageSize : 10,
											curPage : 1,
											id : 'page_1',
											appendTo : this.jq('#pageArea'),				
											loadData : function( page, fn){
												self.goPage(page);
												//self.load();
												fn && fn()
											}	
										});
							}
						},
                        onViewReady : function() {
                            var focusCS = 'style-focus';
                            this.jq('textarea').bind({
                                focus: function(){
                                    $(this).addClass(focusCS)
                                },
                                blur : function(){
                                    $(this).removeClass(focusCS);
                                }
                            })
                        }
                    });
                    cmt.display(1);
                    cmt.load();
				
			}
			
		})
		
        //分享游记，flash部分 /youji.share/id-122571
        .reg('youji.sharePic', {
            ui : {
                imgs : '',
                
                flashId : 'youji_share_flash',
                
                actionMgr : true,
                
                onactiontrig : function(e) {
                    var data = e.data;
                    switch (data.e) {
                    case 'flashShareRefresh':
                        this.flashCall('reset', this.getRandImgs());
                    break;
                    }
                },
                getRandImgs : function() {
                    if (!this.imgs) return {};
                    
                    var ret = {} , imgs = this.imgs;
                    var rands = Util.arrayRand(imgs, 4);
                    $.each(rands, function(i,r){
                        ret['img_' + (i+1)] = r;
                    });
                    
                    return ret;
                    
                },
                
                initPic : function(imgs) {
                    if (!imgs || !imgs.length) {
                        return;
                    }
                    
                    this.imgs = imgs;
                    
                    var basePath = X.getCfg('basePath');
                    var flashvars = {
                        youji_id : '',
                        _PHPSESSID : $('#_PHPSESSID').val(),
//                        upload : '',
                        flashFun : 'flashFunc',
                        jsFunc : 'flashCallBack'
                    }
                    
                    flashvars = $.extend(flashvars, this.getRandImgs());
                    
                    var params = {
                        AllowScriptAccess:"sameDomain",
                        wmode:"transparent"
                    };
                    swfobject.embedSWF( basePath + 'flash/imgPro.swf?v=' + X.getCfg('subver'), this.flashId, "306", "349", "10.0.0", "expressInstall.swf", flashvars, params);
                    
                    window.flashCallBack = Util.bind(this.flashCallBack, this);
                    
                    this.jq('#btn_change').cssDisplay(1);
                },
                
                //flash 回调 type: imgString ready
                flashCallBack : function(type, data){
                    switch (type) {
                    case 'imgString':
                        if (this.callBackFunc[type]) this.callBackFunc[type](data);
                    break;
                    }
                },
                
                callBackFunc : {},
                
                //调用falsh方法 
                flashCall : function(func, data) {
                    try{          
                        return swfobject.getObjectById(this.flashId).flashFunc(func, data);
                    }catch (e) {
                        return null;
                    }
                }
            },
            
            onViewReady : function(cfg) {
                var ui = this.getUI(),
                    data = cfg.data;
                ui.initPic(data.imgs);
            }
        })
        
        .reg('youji.shareMain', {
            ui :{cls : X.ui.ShareByChoose},           
            onViewReady : function(cfg) {
                if (cfg && cfg.data) {
                    this.getUI().youji_id = cfg.data.youji_id;
                }
                
                var $droplist = this.jq('#droplist');
                var $searchInput = this.jq('#friends_search');
                
                function isEmpty(val) {
                    return !val || val == '输入好友昵称..';
                }
                
                function chkEmptyInput(e){
                    var type = e.type;
                    if (isEmpty(this.value)) {						
                        if (type == 'focus') {							
                            $droplist.html('<a href="javascript:void(0);" id="focus">输入昵称搜索好友...</a>');
                            $droplist.cssDisplay(1);
                        } else {
                            $droplist.cssDisplay(0);
                        }
                    }
                }
                $searchInput.focus(chkEmptyInput)
                .blur(chkEmptyInput)
                .keyup(chkEmptyInput);
            }
        })
		
		//好友动态
		.reg('message.dynamic', {			
			onViewReady : function(cfg){
				var ui = this.getUI(), recommend = cfg.data.recommend, len = recommend !=''? recommend.total_number : "";
				var dynamic = getCfg('userCfg').dynamic_recommend , ld = '', trends = '';
				
				function createTrend(){
					if(ld == '') return;
					var intros = recommend.list;
					trends =  X.use('Box', {
						cs:'win-fixed win-trends',
						contentHtml : 'trends',
						appendTo : document.body,
						closeable:true,
						mask:true,
						actionMgr:true,
						onactiontrig:function(e){
							switch(e.data.e){
								case 'ac' :
									this.send();
								break;
								default :
								e.stopPropagation(false);
							}
						},
						
						send : function(){
							var ids = [];
							for(var k in ld){
								ids.push(ld[k].id);								
							}
							
							if(ids.length)
								Req.follow(ids.join(','), 0, function(e){
									if(e.isOk()){
										//Box.success('','关注成功',function(){
											Req.setRemind('dynamic_recommend',1,function(){
												location.reload();			
											});																						
										//});																					
									}else{
										if(e.getCode() == '1411104'){
											//Box.success('','关注成功',function(){
												//location.reload();													
											//});	
											Req.setRemind('dynamic_recommend',1,function(){
												location.reload();			
											});		
										}else 
											Box.alert('',e.getMsg());										
									}									
								});							
						},
						
						close : function(){
							X.ui.Box.prototype.close.call(this);
							if(dynamic != 1)
								Req.setRemind('dynamic_recommend',1,function(){});	
						},
						onViewReady  : function(){
							var ul = this.jq('ul'), lis = [], T = X.ax.Tpl;
							var li = '<li><div class="pic">'+
                                '<a href="{.url}"><img src="{.face_m}" alt="" /></a></div>'+
								'<div class="info">'+
									'<p class="name"><a href="{.url}" title="{.nickname}">{.nickname}</a></p>'+
									'<p class="desc">{.intro}</p>'+
									'<p class="operate">[?.follow?<a href="#" title="" rel="e:fl,t:9,u:{.id}"><i>+</i> 加关注</a>?][?.followed?<span class="ico-followed-s2">已关注</span>?]</p>'+
								'</div></li>';
							for(var k in ld){
								var user = ld[k];
								user.url = Req.mkUrl('space','ta', {id:user.id});
								user.intro = intros[k];
								if(user.friendship == 1 || user.friendship){
									user.followed = 1;
								}else{
									user.follow = 1;
								}
								lis.push(T.parse(li, user));			
							}							
							ul.html(lis.join(''));							
						}
					}).display(1);
					
				};
				
				
				//获取点评赞成反对
				function getTipsIds(data){
					if(data.fdname == 'tipsSpot') return data.data.tips_id;
					return '';
				}
				
				function setStateByIds(data, jqCt){
					var len = jqCt.length, dlen = data.length;
					for(var i=0;i<dlen;i++){	
						var st = data[i].status.st;
						if(st == 0) continue;
						var id = data[i].id;
						for(var j=0;j<len;j++){
							var rel = jqCt.eq(j).attr('rel');
							if(!rel) continue;							
							if(Util.parseKnV(rel).c == id){
								var as = jqCt.eq(j).find('.operate>a');
								if(st == 1 || st == 3){
									as.eq(0).replaceWith('<span class="ico-agree">'+as.eq(0).html()+'</span>');
								}
								if(st == 2 || st == 3){
									as.eq(1).replaceWith('<span class="ico-oppose">'+as.eq(1).html()+'</span>');
								}
								break;
							}
						}
					}
				};
				
				function getStateByTipsIds(ids, dom){
					if(ids.length)
						Req.getStateByTipsIds(ids.join(','),function(e){
							if(e.isOk()){
								var data = e.getData();
								if(data && data.tips && data.tips.length)
									setStateByIds(data.tips, dom);
							}
						});
				}
			
				
				var ids = [];
				$.each(cfg.data.feed,function(i,item){
					var id = getTipsIds(item);
					id && ids.push(id);
				});
				
				getStateByTipsIds(ids, $('#feedLists>li'));
				
				
				if(cfg.data.feed.length == 0 && dynamic != 1 && len !='0' ){
					ld = recommend.users;
					createTrend();
					
				}else{
					var maxPage = 10;
					cfg.data.url && X.use('ScrollLoad',{jqCt:$('#feedLists'),url:cfg.data.url
					,maxPage : maxPage
					,scrollLoadAfter : function(d){
						var htmls = $.trim(d.html), htmls = $(htmls);
						
						var lists = $(htmls.html()).appendTo(this.jqCt);
						//this.jqCt.append(htmls.html());
						var ids = [];
						$.each(d.feed,function(i,item){
							var id = getTipsIds(item);
							id && ids.push(id);
						})
						getStateByTipsIds(ids, $('#feedLists>li'));
						this.cb && this.cb(d, htmls);
					}
					,loadError : function(e){
						if(e.getCode() == '1462102'){
							var self = this;
							$('<p class="load-fail"><a href="#">加载失败，点击重新加载</a></p>').appendTo('#feedLists').click(function(e){
								e.preventDefault();
								self.scrollLock = false;
								self.loadData(true);
								$(this).remove();
							});
						}						
					}
					,cb : function(e){
						var jqCt = this.jqCt, self = this;
						if(this.curPage == maxPage){//出现下一页
							ui.jq('#prev').cssDisplay(0);
							ui.jq('#next').cssDisplay(1).attr('href',e.url).click(function(e){	
								e.preventDefault();
								jqCt.html('');
								self.scrollLock = false;
								$(this).cssDisplay(0);
								self.maxPage = maxPage * 2;
								self.loadData(true);
							});
						}
						if(this.curPage>maxPage){//出现上一页							
							ui.jq('#next').cssDisplay(0)
							ui.jq('#prev').cssDisplay(1).attr('href',e.url).click(function(e){
								e.preventDefault();
								location.reload();
							});							
						}
					}});					
				}
				
				$('#toTrends').click(function(e){
					e.preventDefault();
					if(trends == ''){
						ld = recommend.users;
						createTrend();
					}else trends.display(1);						
				});
				
				X.on('public.unread', function(e){
					if(e.isOk()){
						if(e.getData()['msg']>0)
							$('#menuMsg').text('('+e.getData()['msg']+')');		
						else 
							$('#menuMsg').text('');		
					}					
				});
			}	
		})
		
		
		//景点详细页（新版）
		.reg('spots.cover_info_big', {
			onViewReady : function(cfg){
				var ui = this.getUI(), tags = ui.jq('#tagArea>span'), tagBtn = ui.jq('#tagBtn')
				, tagVal = ui.jq('#tagVal'), defaultText = '最多七个字', sid = cfg.data.sid;				
				var act = Xwb.use('ActionMgr',{
					target : ui.jq()
				}).reg('tag',function(e){
					var $e = $(e.src), v = $e.text();
					tagVal.val(v);
					Util.focusEnd(tagVal[0], Util.byteLen(v));			
				}).reg('btn', function(e){
					var v = Util.trim(tagVal.val()), len = Util.byteLen(v);
					if(v == defaultText){
						Box.alert('','请输入印象',function(){
							tagVal.focus();
						});	
						return;
					}
					if(len > 14){
						Box.alert('','最多可输入7个汉字，14个字符',function(){
							tagVal.focus();
						});						
					}else{
						e.lock(1);
						Req.addImpression(sid, v, function(r){
							e.lock(0);
							if(r.isOk()){								
								X.ui.localStorage.set('tagSuc','1');
								location.href = Req.mkUrl('spots','impression',{id:sid,k:v});	
							}else{
								Box.error('',r.getMsg());								
							}							
						});
					}
				});
				
				tagVal.focus(function(e){
					var v = Util.trim(tagVal.val());
					if(v == defaultText){
						this.value = '';
					}
					this.className = 'focus';
				}).blur(function(e){
					var v = Util.trim(tagVal.val());
					if(v == ''){
						this.value = defaultText;
					}	
					this.className = '';
				}).keydown(function(e){
					if(e.keyCode == 13){
						tagBtn.click();
					}
				});	
				
			}
			
		})
		
		//景点印象页
		.reg('spots.spot_impression', {
			onViewReady : function(cfg){
				
				function tagBox(msg){
					var msg = msg || '你认同了该印象';
					var box = Xwb.use('Box', {
						cs:'win-tips-s2 win-agree',
						contentHtml :'<p>'+msg+'</p>',
						appendTo : document.body,
						destroyOnClose : true,
						onViewReady : function(){
							setTimeout(function(){box.close()}, 2000);
						}
					});						
					box.display(true);	
				}
				
				if(X.ui.localStorage.get('tagSuc')){	
					X.ui.localStorage.set('tagSuc','')
					tagBox('你认同了该印象');
				}
				
				var ui = this.getUI(), tagBtn = $('#tagBtn'), tagVal = $('#tagVal'), defaultText = '最多不超过七个字';	
				
				ui.jq('#showAll').click(function(e){
					e.preventDefault();
					$(this).parent().cssDisplay(0);
					ui.jq('#allTags').show();
				});
				
				tagVal.focus(function(e){
					var v = Util.trim(tagVal.val());
					if(v == defaultText){
						this.value = '';
					}
					this.className = 'style-normal style-focus';
				}).blur(function(e){
					var v = Util.trim(tagVal.val());
					if(v == ''){
						this.value = defaultText;
					}	
					this.className = 'style-normal';
				}).keydown(function(e){
					if(e.keyCode == 13){
						tagBtn.click();
					}
				})
				
				function setTags(lists,n){					
					var len = lists.length, has = '';
					for(var i=0;i<len;i++){
						var li = lists.eq(i);
						if(li.hasClass('tag-added')){
							li.removeClass('tag-added');
						}
						if(li.text() == n && li.text() != '全部'){

							li.addClass('tag-added');
							has = li;
						}
					}
					return has;
				}
				X.use('ActionMgr',{
					target : $('#impression').parent()
				}).reg('btn', function(e){
					var v = Util.trim(tagVal.val()), len = Util.byteLen(v);
					if(v == defaultText){
						Box.alert('','请输入印象',function(){
							tagVal.focus();
						});	
						return;
					}
					if(len > 14){
						Box.alert('','最多可输入7个汉字，14个字符',function(){
							tagVal.focus();
						});						
					}else{
						e.lock(1);
						Req.addImpression(cfg.data.sid, v, function(r){
							e.lock(0);
							if(r.isOk()){
								tagVal.val('');
								var has = setTags($('#sectionTags a'), v);
								var allTags = $('#allTags');
								if(allTags.length)
									has = setTags($('#allTags a'), v);
								if(has) has.addClass('tag-added');
								else{
									tagBox('你认同了该印象');
									var addParent = $('#sectionTags');
									if(allTags.length) addParent = allTags;
										addParent.append('<a title="1人认同该印象" class="tag-s2  tag-added" href="#">'+v+'</a>');
									
								}
							}else{
								if(r.getCode() == '1425006'){
									tagVal.val('');
									setTags($('#sectionTags a'), v);
									var has = setTags($('#allTags a'), v);
									if(has) has.addClass('tag-added');
									tagBox('你已认同该印象');
								}else{
									Box.alert('',r.getMsg());
								}									
							}							
						});
					}
				}).reg('tag', function(e){
					var $e = $(e.src), v = $e.text();
						e.lock(1);
						Req.addImpression(cfg.data.sid, v, function(r){
							e.lock(0);
							if(r.isOk()){
								ui.jq('.tag-added').removeClass('tag-added');		
								setTags($('#sectionTags a'), v);
								setTags($('#allTags a'), v);	
								tagBox('你认同了该印象');					
								//$e.addClass('tag-added');
							}else{
								if(r.getCode() == '1425006'){
									ui.jq('.tag-added').removeClass('tag-added');		
									setTags($('#sectionTags a'), v);
									setTags($('#allTags a'), v);
									tagBox('你已认同该印象');
								}else{
									Box.alert('',r.getMsg());
								}						
							}							
						});
				});
				
			}
		})
		
		.reg('spots.detail_map', {
			onViewReady : function(cfg){
				var data = cfg.data;
				if(data){
					var ui = this.getUI(), initCenter = cfg.data.lat+','+cfg.data.lng, self = this, _zoom = cfg.data.zoom, zoom = 11;
					switch(_zoom){
						case 'spot':
							zoom = 12;
							break;
						case 'continent':
							zoom = 2;
							break;
						case 'country':
							zoom = 3;
							break;
						case 'province':
							zoom = 4;
							break;
						case 'dest':
							zoom = 7;
							break;						
					}
					//异步加载google map
					X.on('pipe.end', function(){					
						X.use('LoadBaiduMap').initUI({
								view:ui.getView(),
								rightLists : false, //右边列表
								canClick : false,
								curZoom : zoom,
								canDrag : true,
								unToCenter: true,//不允许居中				
								hasNav : true,
								viewCtl : false,	
								navType : 3,
								center : [cfg.data.lng,cfg.data.lat]								
							}, self, [{lat:cfg.data.lat,lng:cfg.data.lng}]);
					});	
				}
				
			}
			
		})
		
		.reg('spots.sub_items', {
			onViewReady : function(cfg){
				var data = cfg.data, lists = data.geo, ui = this.getUI(), center = [], self = this, parent = ui.getView(), sid = data.sid;
				
				function resetData(d){
					var i = 0;
					for(var key in d){
						var _list = d[key];
						if(i == 0)center = [_list.lng,_list.lat];
						_list.id = i;
						_list.state = {img:'/img/googleMapMark.png'
						,size:[20,33],points:i*34};
						i++;
					}
					return d;
				}
				resetData(lists);
				if(center)
					X.on('pipe.end', function(){
						X.use('LoadBaiduMap').initUI({
								view:parent,
								rightLists : false, //右边列表
								canClick : false,
								zoom : 11,
								center : center,
								unToCenter: true,//不允许居中
								navType : 3,
								viewCtl : false
							}, self, lists);
					});
				Xwb.use('ActionMgr',{
					target : ui.jq()
				}).reg('to',function(e){
					var id = e.get('id'), spots = lists[id];
					if(spots){		
						self.ui.setCenter(spots.lng, spots.lat);
					}
				});
				
				if(data.total>0 && data.total/(data.count||10)>1)
				X.use('Page',{
					total : data.total,
					pageSize : data.count||10,
					curPage : 1,
					appendTo : $('#pageArea'),				
					id : 'pagePart_1',
					loadData : function(page, fn){
						var _t = this;
						self.ui.removeAll();
						Req.getSpotsSub(sid, page, function(r){
							 _t.lock = false;											
							if(r.isOk()){
								fn && fn();//修改分页符
								var _re = r.getData();
								lists = _re.geo;
								self.ui.addFoots(resetData(_re.geo));
								self.ui.setCenter(_re.geo[0].lng,_re.geo[0].lat);
								ui.jq().html(_re.html);
							}
						})
					}	
				});
				
				var mapArea = $('#mapArea'), t = mapArea.offset().top;
				$(window).scroll(function(){
					var st = $(document).scrollTop();
					if( st + 55 > t ){
						$('#mapArea').addClass('fixed');
					}
					else {
						$('#mapArea').removeClass('fixed');
					}
				});
			}			
		})
		
//点评详细列表		
		.reg('spots.detail_tips', {
			onViewReady : function(cfg){
				var sid = cfg.data.sid, ui = this.getUI(), sort = cfg.data.tipsType, parent = ui.jq(), curCmt = null
				init = false, tid = cfg.data.tid, count = cfg.data.count, weibo = {}, replyv = '', items = [];	
				
				tid = tid == '0' ? '':tid;
				items.push({ id : '#cmt_0', state : 0 });
				for(var i in sort){
					var obj = { id : '#cmt_' + i, state : i }
					items.push(obj);
				}
				X.use('SwitcherExt', {					
					items :items,
					actoinObj : 'markParent',
					setTab : function(o){
						var p = o.parent().parent(), s = p.find('span'), oldRel = s.attr('rel'), oparam = Util.parseKnV(oldRel), newRel = o.attr('rel'), nparam = Util.parseKnV(newRel) ;
						s.parent().removeClass('cur');
						o.parent().addClass('cur');
						s.replaceWith('<a href=# rel="'+oldRel+'">'+s.text()+'</a>');
						parent.find('#cmt_'+this.items[this.resetIndex(oparam.s)].state).hide();	
						o.replaceWith('<span rel="'+o.attr('rel')+'">'+o.text()+'</span>');
						
						sort = this.items[this.resetIndex(nparam.s)].state;
						return true;
					},
					
					getPart : function(data){
						var footmark = parent.find('#cmt_'+data.state);
						if(footmark.length){
							footmark.show();
						}else{
							cmtUI(data.state);
						}
					},
					
					resetIndex : function(num){
						for(var i = 0; i < this.items.length; i++){
							if(num == items[i].state){
								return i;
							}
						}
					},
					toPage : function( p ){
						var data = this.items[this.resetIndex(p.s)];			
						//显示列表
						var old = this.getJq(this.cur.id).hide();
						this.cur = data;
						var news = this.getJq(data.id);
						if(news.length == 0){
							this.getPart(data);
						}else{
							news.show();
						}
						
					}
				}); 
				
				ui.jq('#toPointCmt, #_toPointCmt').click(function(e){
					e.preventDefault();
					if(curCmt){
						$(document).scrollTop(curCmt.cmtBox.jqInputor.offset().top);
						curCmt.cmtBox.jqInputor.focus();	
					}
				});	
				
				var uid = getCfg('uid');
				if(uid)
					Req.bindLst(getCfg('uid'), function(rd){		
						if(rd.isOk()){
							weibo = rd.getData();
						}
					});
				
				function cmtUI(sort, fn){
					init = false;
					var cmt = X.use('CmtArea', {
						wbId :  sid,
						wbUid :  sid,
						newSystem : true,
						showEmotion : false,
						profileImg : getCfg('face_m') || '/img/default.png',
						appendTo: ui.jq(),
						trigEl : '#b_comment',
						view : 'PointCommentArea',
						maxLen: 140*2,
						cmtType : sort,
						localComments : false,
						startPage : 1,
						type : 'pointComment',
						shareWb : true,
						commentHtml : 'PointCmt',
						commentUrl : Req.pointComment,
						replyUrl : Req.pointComment,
						afterSend : function(){
							Box.tipOk('点评成功');
						},
						//点评成功
						_afterSend : function(e){
							if(e.isOk()){
								if(this.jqCmtCt.find('li').length == 0){
									this.jqCmtCt.parent().find('.tips-null-s2').remove();
								}
								var jq = $(this.createCmtUI(e.getData().comment || e.getData().data || e.getData()));
								this.jqCmtCt.prepend( jq );
								this.jqCmtCt.cssDisplay(true);
								this.updateCmtCountUI(1, true);
								this.itemHover(jq);
								if(getCfg('uid'))
									X.use('usersCard',{items:jq.find('.user_card')});
								$(document).scrollTop(this.jqCmtCt.offset().top-45);
							}
						},
						
						//焦点位置
						toPonitCmt : function(e){
							if(curCmt){
								$(document).scrollTop(curCmt.cmtBox.jqInputor.offset().top);
								curCmt.cmtBox.jqInputor.focus();	
							}
						},
						//获取点列表
						getCommentUrl : function(sid,page,type,fn){
							var sTid = '';
							if(!init){
								init = true;								
								page = 0;
								sTid = tid;//第二次请求tid没有作用
							}else{
								page = (page - 1)*count;
							}
							Req.getPointComments(sid,page,type,tid,fn);
							
							
						},
						//填写点评输入框内容
						replyList : function(ja, cmtId, nick){
							if(tid){//回复点评
								nick = cfg.data.nick || nick;
								cmtId = cfg.data.cmtId || cmtId;
							}
							replyv = '回复@' + nick + ': ';
							ja.val(replyv);
							ja.data('reply_cid', cmtId);
							Util.focusEnd(ja[0], Util.byteLen(replyv));	
						},
						
						//赞同
						setUseful : function(e, v){
							e.lock(1);
							Req.setUseful(e.get('c'), v, function(r){	
								e.lock(0);
								if(r.isOk()){
									var $s = $(e.src).find('span'), num = Number($s.text());
									$s.text(num+1);									
								}else{
									Box.tipError(r.getMsg());
								}
							});
						},
						
						//打开回复框
						replyPage : function(e){
							var je = $(e.src), parent = je.closest('#comment_c'), cmtId = e.get('c'), nick = e.get('n');
							if(je.data('has')){
								var hidden = parent.find('#replyListArea').hasClass('hidden');
								parent.find('#replyListArea').cssDisplay(parent.find('#replyListArea').hasClass('hidden'));
								if(hidden) this.replyList(parent.find('textarea'), '_', nick);								
							}else{
								parent.append(X.ax.Tpl.tpls.PointReplyListArea);
								je.data('has',1);
								this.getReplyPage(0, cmtId, parent, Util.bind(this.createPage, this));
								this.replyList(parent.find('textarea'), '_', nick);								
							}							
						},
						
						//获取回复点评列表数据
						getReplyPage : function(page, cmtId, parent, fn){
							var self = this;
							Req.getPointReplyList(sid, cmtId, page*5,function(e){
								if(e.isOk()){
									var data = e.getData();
									self.showList.call(self, data.replies, parent);
									fn(data, parent, cmtId);
								}
							});
						},
						
						//显示回复点评列表
						showList : function(data, parent){
							var lists = [], T = X.ax.Tpl;
							for(var k in data){
								lists.push(T.parse( T.tpls.PointReplyList, data[k]));			
							}
							parent.find('#replyList').html(lists.join(''));
						},
						
						//创建回复点评列表分页
						createPage : function(d, parent, cmtId){
							var cmt = this;
							if(d.next_cursor != -1)
								X.use('Page',{
									total : d.total,
									pageSize : d.count,
									pageModel : function(big, leftLine, rightLine){
										var pageHtml = [], first = true;
										if(this.curPage == 1){//上一页
											pageHtml.push('<span class="disable">上一页</span>');			
										}else{
											pageHtml.push('<a href="#" rel="e:t,na:1,n:'+(this.curPage-1)+'">上一页</a>');
											if(this.begin != 1) pageHtml.push('<a href="#" rel="e:t,na:1,n:1">1</a>');
										}
										for(var i = this.begin; i<=big; i++){
											if(first && leftLine) pageHtml.push('<span>...</span>'); 
											first = false		
											if(i == this.curPage) pageHtml.push('<span class="nullCur">'+i+'</span>');
											else pageHtml.push('<a href="#" rel="e:t,na:1,n:'+i+'">'+i+'</a>');									
										}
										
										if(rightLine){//下一页
											pageHtml.push('<span>...</span>');				
										}
										
										if(this.totalPage == this.curPage){
											pageHtml.push('<span class="disable">下一页</span>');			
										}else{
											if(big != this.totalPage)pageHtml.push('<a href="#" rel="e:t,na:1,n:'+this.totalPage+'">'+this.totalPage+'</a>');	
											pageHtml.push('<a href="#" rel="e:t,na:1,n:'+(this.curPage+1)+'">下一页</a>');
										}										
										this.jq().html(pageHtml.join(''));
									},
									curPage : 1,
									appendTo : parent.find('#pageArea'),				
									id : 'pagePart_'+cmtId,
									loadData : function(page, fn){
										var self = this;
										cmt.getReplyPage(page-1, cmtId, parent, function(rd){
											//cmt.showList(rd.getData(), parent);
											fn();
										});
									}	
							});
						},
						//回复点评
						pointReply : function(e){
							var cmt = this, jq = $(e.src), cmtArea = jq.closest('#replyListArea'), jtext = cmtArea.find('textarea'), text = Util.trim(jtext.val());
							if(Util.byteLen(text)>140){
								Box.alert('','输入的内容不能超过140个字');
							}else{
								var replyCmtId = jtext.data('reply_cid'),
									regx = new RegExp('^回复@.*?: ')
									cid = e.get('c');										
								if( replyCmtId && regx.test(text) ){
									e.lock(1);
									Req.pointReply(sid, cid, replyCmtId=='_'?'0':replyCmtId, text, function(r){		
										e.lock(0);									
										if(r.isOk()){
											jtext.val(replyv);
											var T = X.ax.Tpl, items = cmtArea.find('#replyList div.item');
											var _item = T.parse( T.tpls.PointReplyList, r.getData());							
											if(items.length)
												$(_item).insertBefore(items.eq(0));
											else
												cmtArea.find('#replyList').append(_item);
												
											var ra = cmtArea.closest('li').find('span.operate #r'), num = Number(ra.text());
											ra.text(num+1);				
										}else{
											Box.alert('',r.getMsg());
										}
									});
								}else{
									Box.alert('','请认真填写回复内容');
								}
							}							
						},
						
						pointListReply : function(e){
							var jq = $(e.src), n = e.get('n'), cmtId = e.get('r'), jtext = jq.closest('#replyListArea').find('textarea');
							this.replyList(jtext, cmtId, n);
						},
						//删除点评
						onDelTrig : function(e){
							e.lock(1)
							Box.anchorConfirm(e.src, getText('确定要删除该点评吗？'), function(bid){
								if(bid === 'ok'){										
									Req.delPointReply(e.get('c'), '', function(re){
										if(re.isOk()){
											$(e.src).closest('li').remove();
										}else{
											Box.alert('',re.getMsg());
										}
										e.lock(0);
									});
								}
							});
						},
						
						onViewReady : function() {
							var focusCS = 'style-focus';
							this.jq('textarea').bind({
								focus: function(){
									$(this).addClass(focusCS)
								},
								blur : function(){
									$(this).removeClass(focusCS);
								}
							});
							this.cmtBox.comment = function(sid, text ,v1, v2, fn){
								var st = [], ipts = $(cmt.cmtBox.view).find('input[name="weibo"]:checked'), len = ipts.length;
								for(var i=0;i<len;i++){
									st.push(ipts[i].value);
								}
								Req.pointComment(sid, text, st.join(','), fn);
							}
							
							//点评分享
							this.cmtBox.shareWeibo = function(e){
								var $e = $(e.src), t = e.get('t');
								if(weibo[t]){
									$e.attr('checked',$e.attr('checked'));
									e.preventDefault(false);
								}else{
									var authLog = X.mod.authLogin;
									authLog.onPopupCallback = function(nickName){
										this.logWin.close();
										$e.attr('checked',true);
										weibo[t] = true;
									};
									authLog.logFail = function( errcode ){
										this.logWin.close();
										if( errcode == '417407' )   //提示:第三方帐号已绑定
											Box.alert("提示",Req.ERRORMAP[ errcode ] );
										else Box.error("提示",Req.ERRORMAP[ errcode ] || "未知错误");
									}
									window.bind3PartSucc = Util.bind(authLog.onPopupCallback, authLog);
									window.bind3PartFail = Util.bind(authLog.logFail, authLog);
									authLog.open2( t, 'bind' );
								}
								
							};
							$(this.view).attr('id','cmt_'+sort);
							
							//最新点评
							//if(sort == 1){
								X.on('tipsApi.add',Util.getBind(this,'_afterSend') );
							//}
							var self = this;
							//if(tid){//从其它地方点击过来,要展开指点回复
							
								X.on('tipsApi.listData',function(e){
									if(tid){//从其它地方点击过来,要展开指点回复
										var obj = self.jqCmtCt.find('li[rel^="c:'+tid+'"]');
										if(obj.length == 1){
											$(document).scrollTop(obj.offset().top - 45);
											obj.find('.operate a._r').click();
										}
										tid = '';
									}
									
									fn && fn();
									X.un('tipsApi.listData');
								});		
								
						},
						
						afterShow : function() {
							//检测url Hash ，如果是comment，则focus到输入框
							if (location.hash == '#comment') {
								$(document).scrollTop(this.jq().offset().top-75);
								this.jq('textarea').focus();
							}
						}
					});
					cmt.display(1);
					cmt.load();	
					curCmt = cmt;
					
					parent.data('sort_'+sort, cmt);
				}				
				cmtUI(0);
			}
			
		})
		.reg('show.calendar',{
			onViewReady: function( cfg ){
				var thisPlet = this;
				thisPlet.data = cfg.data;
				
				var ui =  this.getUI(),
					jq = ui.jq();
				var uCard = X.use('Box',{
					view : $('#uCard2')[0],
					onViewReady : function(){
						var self = this;
						var mouseInside = false;
						$(this.view).hover(
							function(){
								mouseInside = true ;
							},
							function(){
								mouseInside = false;
								setTimeout(function(){
									!mouseInside && self.display(0);
								},50);
							}
						);
					},
					anchorShow : function( anchorElm, lr, date ){
						var pos = $(anchorElm).offset();
						var $view = $(this.view);
						
						if(!thisPlet.data.users[date])
							return ;
						var pars = $.extend({}, thisPlet.data.users[date]);
						pars.show_date = pars.show_date.substring(8);
						pars.imgSrc = eval('0,'+pars.show_pic).avatar;
						pars.yuyuLink = Req.mkUrl('show','detail') + '&id=' + pars.uid;
						pars.summary = pars.summary.replace(/<[^<]*>/g,'');
						
						$view.find('#hoverCont2').html( X.ax.Tpl.parse('yuyuShow2', pars) );
						
						pos.top -= 5, pos.left -= 5;
						$view.css(pos);
						var ml = lr == 'left' ? 130 : -125;
						$view.find('#contt').css({'marginLeft':0})
											.animate({marginLeft: ml}, 400);
						this.display(1);
					}
				});
				
				var thisPagelet = this;
				$('#container').delegate('.user-list li','mouseover',function(){
					var dateKey = this.getAttribute('dateKey');
					if( dateKey ){
						var n = this.getAttribute('n');
						uCard.anchorShow( this, n%7 < 4 ? 'left' : 'right', dateKey );
					}
				}).delegate('li','click',function(){ //上月下月
					var day = this.getAttribute('day'),
						n = this.getAttribute('n'),
						month = thisPagelet.data.month,
					    year = thisPagelet.data.year;
					if( day>20 && n < 8 ){
						thisPagelet.changeMonth(year,month, 'prev', this);
					}
					else if( day<8 && n>27 ){
						thisPagelet.changeMonth(year,month, 'next', this);
					}
					return false;
				});
				X.use('action').reg('prevm', function(e){
					if( !thisPagelet.changeMonth(  thisPagelet.data.year, thisPagelet.data.month, 'prev', e.src ) )
						e.src.className = 'btn-s4 btn-s4-disabled';
					return false;
				})
				.reg('nextm',function(e){
					if( !thisPagelet.changeMonth( thisPagelet.data.year, thisPagelet.data.month, 'next', e.src ) )
						e.src.className = 'btn-s4 btn-s4-disabled';
					return false;
				});
			},
			changeMonth: function( year, month, action, elm){
				if( elm && elm.getAttribute('locked') )
					return false;
				elm.setAttribute('locked','locked');
				var startYMR = this.data.start.split('-'),
					endYMR = this.data.end.split('-');
				if( startYMR.length !== 3 ){
					return false;
				}
				action = action || 'next';
				if( action == 'prev' ){
					month--;
					if( month<=0 ){
						month = 12;
						year--;
					}
					if(  ( year < parseInt(startYMR[0]) ) ||  
					     ( year == parseInt(startYMR[0]) &&  month < parseInt(startYMR[1]) ) ){
						return false;
					}
				}else{
					month++;
					if( month>12 ){
						month = 1;
						year++;
					}
					if(  ( year > parseInt(endYMR[0]) ) ||  
					     ( year == parseInt(endYMR[0]) &&  month > parseInt(endYMR[1]) ) ){
						return false;
					}
				}
				this.calendarChange(year,month);
				return true;
			},
			calendarChange: function( year, month ){
				var thisPlet = this;
				Xwb.request.jsApiCall('show','calendar', 'year='+year+'&month='+month, function(r){
					if(r.isOk()){
						var data = r.getData();
						thisPlet.data = data;
						var $newCalendar = $( data.html );
						$('#calendar').find('div.actions').replaceWith( $newCalendar.find('div.actions') );
						$('#calendar').find('ul.user-list').animate({'opacity':0},'slow',function(){
							var $newList = $newCalendar.find('ul.user-list');
							$newList.css('opacity',0);
							$(this).replaceWith( $newList );
							$newList.animate( {'opacity':1}, 'slow');
							$newCalendar = null;
						})
					}
				});
			}
		})
		.reg('show.youji',{
			onViewReady: function( cfg ){
				$('div.travel-notes div.filter').append($('<span class="other">共<span>'+cfg.data.total_number+'</span>篇</span>'));
			}
		})
		
		//景点图片页
		.reg('spots.pic_main', {
			onViewReady : function(cfg){
				var url = cfg.data.url, T = X.ax.Tpl;
				X.use('ScrollLoad',{jqCt:$('#picLists'),ajax:Req.getReq, url:url
					,maxPage : 100
					,createItem : function(item){
						return T.parse( T.tpls.SpotsPic, item);
					}
					,scrollLoadAfter : function(d){			
						var has = false, data = d.pics, srcList = [];
						for(var k in data){
							var li = $(data[k].html).appendTo(this.jqCt), img = li.find('img')[0];
							srcList.push(data[k].pic.url);
							Util.drawImage(img, 200, 135,function(obj){});
							has = true;
						}
						if(!has){
							this.jqCt.html('<li>暂无图片<li>');
						}else{
							X.cfg.srcList = srcList;
						}

						//this.jqCt.append(htmls.join(''));

				}}).loadData(true);
			}
		})
		//开通码头
		.reg('center.guide_users',{
			onViewReady : function( cfg ){
				var url = cfg.data.url;
				url && this.getUI().jq('div.right-info').attr('nextPageUrl', url);    //该属性与下面的center.guide_spots pagelet有关，表示 是否 还可以 换一批 好友
			}
		})
		//开通码头
		.reg('center.guide_spots',{
			onViewReady : function( cfg ){
				var jqWrap = $('div.main'),
					$stepCons = jqWrap.find('div.step-con'),
					stepConsHeight = [216,210,$stepCons.eq(2).height()],  //每一部分的高度
					foldHeight = 28,    //折起高度
					$tripBox = $stepCons.eq(2),  //难忘旅途内容区域上
					nameHash = ['group','user','spot'];
					
				$stepCons.each(function(i,item){
					$(item).css({'position': 'relative','overflow':'hidden'});
					$(item).css('height', foldHeight);
				});
				var currentStep = 0;
				expan( currentStep );  //展开第一个
				
				//折叠
				function collap(i){
					if( i < stepConsHeight.length ) {
						var $stepCon = $stepCons.eq(i);
						$stepCon.animate( { height: 30 } );
						$stepCon.find('.hd>.right-info').html('<a href="#" rel="e:expan,curStep:'+i+'">编辑完善</a>');
					}
				}

				//展开
				function expan( i, notAnimate ){
					if( i < stepConsHeight.length ) {
						var $stepCon = $stepCons.eq(i);
						$stepCon.find('div.hd').addClass('highlight');
						if( currentStep != i )
							collap(currentStep);
						if( i == 2 ){
							setSubmitBtnState();
							stepConsHeight[i] = 231 + jqWrap.find('ul.selected-list').height();
						}
						currentStep = i;
						$stepCon.animate( { height: stepConsHeight[i] } );
						
						var btnHtml = '<a href="#" rel="e:cc,t:'+nameHash[i]+'">换一批</a>';
						if( i == 0 && $stepCon.find('li').length < count )
							btnHtml = '';
						else if( i == 1 ){   //根据pagelet给的url判断是否有换一批
							var url = $stepCon.find('div.right-info').attr('nextPageUrl');
							if(!url) btnHtml = '';
						}
						$stepCon.find('.hd>.right-info').html(btnHtml);
					}
				}
				
				function setSubmitBtnState(){
					var allok = true;;
					for(var i=0;i<nameHash.length;i++){
						if( jqWrap.find('#'+nameHash[i]+'Count').html() == '0' ){
							allok = false;
							jqWrap.find('#'+nameHash[i]+'Warn').removeClass('hidden');
						}
						else jqWrap.find('#'+nameHash[i]+'Warn').addClass('hidden');
					}
					if(allok)	jqWrap.find('#btn_toMyCenter').removeClass('btn-join-center-disabled');
					else jqWrap.find('#btn_toMyCenter').addClass('btn-join-center-disabled');
				}
				X.on('setSubmitBtnState',setSubmitBtnState);
				
				//删除难忘旅途
				function  delSpot( spot_id, name, cbFunc ){
					var noPrefixId = spot_id.replace(/[a-zA-Z]/,'');
					Req.jsApiCall('center','guide_fav_del',{id: noPrefixId}, function(rst){
						if(rst.isOk()){
							$tripBox.find( '#'+spot_id+':checkbox' ).attr('checked',false).parent().removeClass('selected');
							$tripBox.find( '#li_'+spot_id ).remove();
							var $count = $('#spotCount');
							$count.html( Math.max( (+$count.html())-1, 0) );
							cbFunc && cbFunc();
						}
					})
				}
				//添加难忘旅途
				function addSpot( spot_id, name, cbFunc ){
					var spot_name = name || $( '#'+spot_id+':checkbox' ).parent().text(),
						noPrefixId = spot_id.replace(/[a-zA-Z]/,'');
						
					var $selectedlis = jqWrap.find('ul.selected-list li');
					for(var i=$selectedlis.length-1;i>=0;i--){
						var noPrefix_id2 = $selectedlis[i].id.split('_')[1].replace(/^\w/,'');  //去除前缀
						if( noPrefix_id2 == noPrefixId ){
							Box.tip('该景点已经添加');
							return false;
						}
					}	
					
					Req.jsApiCall('center','guide_fav_add',{id: noPrefixId}, function(rst){
						if(rst.isOk()){
							$tripBox.find('ul.selected-list').append( T.parse('spotsItem',{ id: spot_id, name:spot_name} ) );
							var $count = $('#spotCount');
							$count.html( +$count.html()+1 );
							$stepCons.eq(2).height( 231 + jqWrap.find('ul.selected-list').height());
							cbFunc && cbFunc();
						}
					})
				}
				//搜索框
				function setSearchBox(){
					$('#inp_search').addClass('style-normal');
					var x = X.use('search', {
						inputor : $('#inp_search'),
						defaultText : '搜景点',
						focusCS : 'style-focus',
						view : $('body')[0],
						unChange: true,
						catchClick: true,
						onEnter : function(e, row){
							var rid = row.id;
							addSpot( rid, row.name, setSubmitBtnState);
							this.search.reset();
							this.search.display(0);
							$(this.inputor).focus();
						},
						affixfun: function(){ 
							var inpOffset = this.inputor.offset();
						    $(x.search.view).css({
						        left: inpOffset.left,
						        top: !window.XMLHttpRequest ? inpOffset.top+16 : inpOffset.top+26
					        })
						}
					});
				}
				setSearchBox();
				

				//小组换页数据
				var gPage = 0, //换一批当前页
					count = 2,  //每页条数
					itemCount = $stepCons.eq(0).find('li').length,
					maxPage = Math.ceil( itemCount/count ); //最大页数
								//step1 小组初始化设置
				$stepCons.eq(0).find('li:lt('+count+')').removeClass('hidden');
				
				//step2 添加好友 hover效果
				$stepCons.eq(1)
				.find('.pic').each(function(){
					var $me = $(this);
					$me.css('overflow','hidden').hover(function(){
						$me.find('p.intro').css({'display': 'block'}).animate({'bottom':0});
					},function(){
						$me.find('p.intro').animate({'bottom':-50});
					})
				})
				
				//step3 难忘旅途选中交互
				$stepCons.eq(2).find('.selected-list').css('position','relative');  //IE6 overflow 
				$stepCons.eq(2).delegate(':checkbox','click',function(){
					var $me = $(this), $p =  $me.parent('label');
					if( $me.data('lock') == 1 )
						return false;
					$me.data('lock',1);
					function cbfunc(){
						if( $p.hasClass('selected') )
							$me.attr('checked',true);
						else
							$me.attr('checked',false);
						$me.data('lock',0);
						setSubmitBtnState();
					}
					if( $p.hasClass('selected') ){
						$p.removeClass('selected')
						delSpot( this.id, null, cbfunc);
					}
					else{
						$p.addClass('selected');
						addSpot( this.id, null, cbfunc);
					}
					return false;
				})
				
				//进入我的码头
				jqWrap.find('#btn_toMyCenter').click(function(){
					if( $(this).hasClass('btn-join-center-disabled') ){
						return false;
					}
					for(var i=0;i<3;i++){
						if( jqWrap.find( '#'+nameHash[i]+'Count' ).html() == '0' ){
							jqWrap.find( '#'+nameHash[i]+'Warn' ).removeClass('hidden')
							expan( i );
							return false;
						}
					}
					Req.postReq( Req.mkUrl('center','guide'),{finish:1},function(){
						location.href = Req.mkUrl('center');
					},{});
				})

				var spotApiUrl = Req.jsAPI('center','guide_spots');
				X.use('action')
				.reg('cc',function(e){ 				//点击 换一批
					switch(e.data.t){
						case 'group':
							var $lis = $stepCons.eq(0).find('li');
							$stepCons.eq(0).find('li[class!=hidden]').addClass('hidden');
							gPage = (gPage+1) % maxPage;
							for(var i = gPage*count, l=Math.min((gPage+1)*count,itemCount); i<l; i++){
								$lis.eq(i).removeClass('hidden');
							}
							break;
						case 'user':
							var $p = $(e.src).parent();
							var url = $p.attr('nextPageUrl');
							if( !url )
								return ;
							Req.postReq( url, '', function(rst){
								if(rst.isOk()){
									var data = rst.getData();
									if(data.url)
										$p.attr('nextPageUrl',data.url);
									else {
										$(e.src).remove();
										$p.removeAttr('nextPageUrl');
									}
									$stepCons.eq(1).find('.list-s1').html( $(data.html).find('.list-s1').html() );
								}
							}, {});	
							break;
						case 'spot':
							Req.postReq( spotApiUrl, '', function(rst){
								if(rst.isOk()){
									var data = rst.getData();

									spotApiUrl = data.url ? data.url : Req.jsAPI('center','guide_spots'); 
									
									var spots = data.spots, html = [];
									for(var k in spots)
										html.push( T.parse('spotsItem2', spots[k] ) );
									if( html.length ){
										html.push(T.parse('spotsItem2Last'));
										jqWrap.find('ul.triplist').html( html.join('') );
										setSearchBox();  //重置搜索框
									}
								}
							}, {});	
							break;
					}
				})
				//next 下一步
				.reg('next',function(e){
					var i = +e.data.curStep; //当前第几步
					var t = e.data.t;  //类型
					if ( $('#'+t+'Count').html() == 0 ){
						$('#'+t+'Warn').removeClass('hidden');
						return ;
					}
					$('#'+t+'Warn').addClass('hidden');
					collap( i ); expan( i+1 ); e.lock(0);
				})
				.reg('expan',function(e){
					var i = +e.data.curStep;
					expan( i );
				})
				.reg('sel',function(e){  //添加关注 , 取消关注
					e.lock(1);
					var $checkElm = $(e.src).find('a span'),
						methodName = $checkElm[0] ?  'unfollow' : 'follow';
					Req[methodName]( e.data.id, 0, function(r){
						if(r.isOk()){
							var $count = $('#userCount');
							if( methodName ==  'unfollow' ){
								$checkElm.remove();
								$count.html(  Math.max(+$count.html()-1,0) );
							}
							else{
								$(e.src).find('a').append('<span uid="'+e.data.id+'"></span>');
								$count.html(  (+$count.html())+1 );
							}
							setSubmitBtnState();
						}
						else Box.alert('提示',r.getMsg());
						e.lock(0);
					}, {});
				})
				.reg('delSpot', function(e){  //添加难忘旅途
					delSpot(e.data.id, null, setSubmitBtnState);
				})
				.reg('addSpot', function(e){   //添加难忘旅途
					addSpot(e.data.id, null, setSubmitBtnState);
				});
			}
		})
		//头图部分
		.reg('journey.cover', {			
			onViewReady : function(cfg){				
				var ui = this.getUI(), draging = false, ca = ui.jq()
				, operate = ui.jq('#operate'), dragPart = ca.find('#dragPart'),
				org = cfg.data.img,  //原图
				big_pic = cfg.data.big_pic || '',
				uPic = '',//上传时的临时图
				uId = cfg.data.id || '';//上传时的临时图id
				if(operate.length == 0) return;
				ca.hover(function(){		
					if(!draging){
						if(!dragPart.data('drag'))
							operate.cssDisplay(1);
					}
				}, function(){
					if(!draging){
						operate.cssDisplay(0);
					}
				});
				
				ca.find('#dlagingBtn').click(function(e){
					e.preventDefault();
					if(!$(this).data('lock')){
						var et = $(e.target);
						if(et.attr('rel') == 'sa'){ //保存
							operate.data('opt').save(e);
						}else if(et.attr('rel') == 'ca'){//
							operate.data('opt').cancelDrag();
							dragPart.data('drag',false);
						}			
					}
				});
			
				var layer = Xwb.use('Layer', {
					actionMgr : true,
					view : operate[0],
					isShow : false,
					onactiontrig : function(e){
						switch(e.data.e){
							case 'sh' : //显示隐藏
								this.setDisplay();
								if(big_pic){
									this.displayOpt('show');
								}
							break;
							case 'ul' : //上传
								//this.upLoad(e);
							break;
							case 'cp' : //推荐配图
								this.selectPics(e);
							break;
							case 'cd' : //调整位置
								var self = this;
								Util.drawImage(big_pic, 2000,2000, function(obj){
									self.dlag(e, obj, big_pic);
								});		
							break;
							case 'del' : //删除
								this.resetCover(e);
							break;
						}
					},
					//显示调整位置及删除功能
					displayOpt : function(type){
						var dd = operate.find('dd');
						if(type == 'hide'){
							dd.eq(2).hide();
							dd.eq(3).hide();
						}else{
							dd.eq(2).show();
							dd.eq(3).show();
						}
					},
					
					resetCover : function(e){
						//换地图，去掉删除按钮
						var self = this;
						Box.confirm('提示','你确认要恢复默认背景图?',function(id){
							if(id=='ok'){
								e.lock(1);					
								Req.saveCoverList('default', '' ,function(r){
									if(r.isOk()){
										self.displayOpt('hide');										
										org = r.getData().img;										
										dragPart.attr('style','background:url('+org+') no-repeat;');	
									} else {
										Box.error('提示',r.getMsg());
									}
								});
							}
						})
					},
					
					onViewReady : function(){
						this.initUpLoad();
					},
					
					initUpLoad : function(){//上传　
							var upload = ui.jq('#fileIpt')
							, uploading = ''
							, self = this
							, form = ui.jq('#uploadForm')
							, tips = '正在上传图片，请稍候';
							form.cssDisplay(1);
							//setTimeout(function(){upload.click();},0);							
							if(!upload.data('upload')){								
								var up = Xwb.use('UpoadImage', {
								url:Req.jsAPI('journeyApi','uploadCover')
								,fileInput:upload
								,jqForm:form[0]
								,uploadBefore : function(e){//正在上传
									operate.cssDisplay(0);
									draging = true;
									if(uploading) 
										uploading.html(tips).cssDisplay(1);
									else
										uploading = ui.jq('#loading').html(tips).cssDisplay(1);
								}								
								,uploadAfter: function(d){//上传成功回调
									if(d){
										uPic = d.big_pic.url;
										uId = d.id;
										Util.drawImage(uPic, 4000,4000, function(obj){	
											uploading.cssDisplay(0);
											draging = false;											
											self.dlag('', obj, uPic);										
										});										
									}else{
										self.baseSet('');	
									};
							 }});
							 upload.change(function(){
								up.change($(this).val());
							 });
							 upload.data('upload', up);							 
						 }
					},
					
					save : function(e){
						var tp = - this.getPositionY()
						, self = this
						, draging = false;	
						ca.find('#dragTips').cssDisplay(0);
						var optDom = $(e.target).closest('#dlagingBtn');
						if(optDom.data('lock')) return;
						optDom.data('lock',true);
						var tips = ui.jq('#loading').html('正在保存，请稍等').cssDisplay(1);			
						Req.saveCoverList(uId, tp, function(r){
							tips.cssDisplay(0);	
							optDom.data('lock',false);														
							if(r.isOk()){
								var d = r.getData();
								org = d.img;
								big_pic = d.big_pic;							
								Util.drawImage(org, 4000,4000, function(obj){	
									draging = true;
									org = org+'?'+new Date().getTime();
									self.baseSet('background:url('+org+') no-repeat;');		
									self.displayOpt('show');									
								});							
							}else{
								draging = true;
								ca.find('#dragTips').cssDisplay(1);
								Box.alert('', r.getMsg())
							}
						});
						
					},
					
					selectPics : function(e){
						var $e = $(e.src), sbox = $e.data('box'), optObj = this;;
						if(!sbox){
							sbox = Xwb.use('Box', {
								contentHtml : 'selectPics',
								cs : 'win-journey-cover win-fixed',
								title : '推荐配图',
								appendTo : 'body',
								id : 0,
								closeable : true,
								mask: true,
								pics : [],
								actionMgr:true,						
								onactiontrig:function(e){
									switch(e.get('e')){
										case 'c' :
											$(this.view).find('li.cur').removeClass('cur');
											$(e.src).parent().addClass('cur');
											this.id = e.get('id');
										break;
										
										case 's' : //保存
											this.setBackground(e);
											this.display(0);
										break;

										case 'ca' :
											this.display(0);
											break;										
									}
								},
								
								setBackground : function(e){
									var rel = this.jq('li.cur').find('a').attr('rel'), rel = Util.parseKnV(rel);
									
									var imgId = rel.id, self = this;
									var tips = ui.jq('#loading').html('正在保存，请稍等').cssDisplay(1);
									Req.saveCoverList(imgId, '', function(r){
										tips.cssDisplay(0);
										if(r.isOk()){
											operate.cssDisplay(0);
											org = r.getData().img;
											optObj.displayOpt('hide');
											big_pic = '';
											dragPart.attr('style','background:url('+org+') no-repeat;')
										}else{
											Box.alert('', r.getMsg())
										}
									});
								},
								
								onViewReady : function(){
									var self = this;
									Req.getCoverList(function(e){
										if(e.isOk()){
											var html = [];
											$.each(e.getData(), function(i){												
												var cur = this.selected?'cur':'';
												html.push('<li class="'+cur+'"><a href="#" rel="na:1,e:c,id:'+i+'"><img alt="" src="'+this.img_s+'"></a><i></i></li>');
											})
											$(self.view).find('#lists').html(html.join(''));
										}
										
									});
								}
							});
							$e.data('box', sbox);
						}
						sbox.display(1);				
					},	
						
					setDisplay : function(){
						$(this.view).find('dd').cssDisplay(!this.isShow);
						this.isShow = !this.isShow;
						if(this.isShow){
							operate.addClass('activate');
						}else{
							operate.removeClass('activate');
						}
					},
					
					getPositionY : function(){
						var bp = dragPart.css('background-position')
						if(bp){
							return Number(bp.split(' ')[1].replace('px',''))
						}						
						bp = dragPart[0].style.backgroundPositionY.replace('px','');						
						return bp||0;
					},
					
					dlag : function(ev, imgObj, img){
						$(this.view).cssDisplay(0);
						ca.find('div.cont').cssDisplay(0);
						var btn = ca.find('#dlagingBtn').cssDisplay(1) 
						, off = dragPart.data('dragInit');
						ca.find('#dragTips').cssDisplay(1);
						dragPart.data('ob',dragPart.attr('style'))
						.cssDisplay(1).css('cursor','move')
						.css('background', 'url('+img+') no-repeat scroll 0 0 transparent')					
						.data('img', img);
						var cf = ca.offset()
						, cah = ca.height()
						, max = imgObj.height - cah
						, self = this;
						draging = true;
						if(!off){
							off = dragPart.offset();
							dragPart.data('dragInit',off);
							//拖动
							var dlagCom = Xwb.use('DragBase',{max: max, items:dragPart,movePart:$('body'), reset: false, mousemove : function(e, dom){
									if(btn.data('lock')) return;
									var cOff = dragPart.offset()
									, ex = cOff.left, ey = cOff.top
									, cache = dom.data('dragInit')
									, setTop = e.clientY - cache.gap
									, tp = self.getPositionY()
									, ls = e.clientY - Number(cache.e.clientY) + Number(cache.op);
									if(ls < 0 && ls>(-max))
										dragPart.css('background-position','0px '+ls+'px');										
							}, mousedown : function(e, dom){
								X.ui.DragBase.prototype.mousedown.call(this, e, dom);
								var tp = self.getPositionY();
								dragPart.data('dragInit', {e:e, off: dom.offset(), op:tp});		
								$('body').unbind('mouseup', this.mpfn).bind('mouseup', Util.bind(this.mpfn, this));						
							}, mpfn : function(){
								$('body').unbind('mousemove');
							}});
							dragPart.data('dlag', dlagCom);
						}else{
							dragPart.offset(off);
						}				
					},
					
					cancelDrag : function(){
						this.baseSet(dragPart.data('ob'));
					},
					
					baseSet : function(back){
						ca.find('div.cont').cssDisplay(1);
						ca.find('#dlagingBtn').cssDisplay(0);
						ca.find('#dragTips').cssDisplay(0);						
						//back && dragPart.attr('style',back);
						if(Util.ie6){							
							back && Util.setAttr(dragPart[0], 'background:url('+org+') no-repeat;');
						}else
							back && (dragPart.attr('style', back))
						draging = false;
						$(this.view).cssDisplay(1);
						dragPart.data('dragInit','');
						var dg = dragPart.data('dlag');
						dg && dragPart.data('dlag').remove();
						return this;
					}
				}).display(1).display(0);
				operate.data('opt', layer);	
			}	
		})
		
		//旅途列表
		.reg('journey.journeyList', {
			htmlMode : 3,
			onViewReady : function(cfg) {				
				var ui = this.getUI(), v = $('div.journey-list'), hover = true, cache = cfg.data.list;
				ui.view = v[0];
				
				var addIcon = ui.jq('a.btn-add-journey'), points;
				
				//加载下一页
				var jqCt = ui.jq('#seeAll');
				X.use('ScrollLoad',{jqCt:jqCt, url:cfg.data.url
					,maxPage : 100
					,loading : function(T){
						var dom = $('#scrollLoading');
						if(dom.length){
							dom.cssDisplay(T);
						}else{
							$(this.loadHtml).insertBefore(this.jqCt);
						}		
					}
					,scrollLoadAfter : function(d){			
						var has = false, data = d.list, srcList = [];
						for(var k in data){
							cache[k] = data[k];
						}
						var $d = $(d.html);
						
						$d.insertBefore(jqCt);
						addIcon.length && hoverOnItem();
						Out579InIe6();
				}});

				//处理IE6下空地点标签宽度,超过579px
				function Out579InIe6(){
					if(Util.ie6){
						var info_cont = v.find('span.info-cont')
						for(var i=0,len=info_cont.length;i<len;i++){
							var c = info_cont.eq(i).find('span.desc');
							if(c.width()>5){
								Util.setAttr(c[0],'_width:579px');
							}
						}
					}
				}
				//Out579InIe6();   //IE6会无法获取到 width
					
				if(addIcon.length){
					if(!Util.ie6){//IE6不处理
						var jqDoc = $(document), journeyBar = $('#journeyBar'), yearArea = journeyBar.find('#year');
						//计算滚动条位置在那个年份上
						function getScrollItem(scroll){
							var items = v.find('div.item'), cur;
							for(var i=0,len = items.length;i<len;i++){
								cur = items.eq(i);							
								if(cur.offset().top > scroll){
									var i = cur.find('i.arrow').attr('rel');
									if(i == '0'){
										yearArea.text('某年')
									}else if(i){
										var time = Number(i);
										if(time){
											var jt = time*1000, year = '';
											if(jt){
												jt = new Date(jt);
												year = jt.getFullYear();
												yearArea.text(year+'年')
											}	
										}else
											yearArea.text(i)
									}
									break;
								}
							}
						}
						$(window).bind('scroll',function(){
								var st = jqDoc.scrollTop();
							if(st>355)
								journeyBar.cssDisplay(1);
							else
								journeyBar.cssDisplay(0);
								
							getScrollItem(st);
						})
					}					
					
					
					//修改签名
					var signReal = ui.jq('#signReal'), signEdit = ui.jq('#signEdit');
					X.use('action').reg('signed',function(e){
						var txt = $.trim(signReal.cssDisplay(0).find('span').text());
						if(txt == '“这个人很懒，还没有写签名”') txt = '';
						else{
							var arr = /^\“(.+)\”$/.exec(txt);
							if(arr){
								txt =  arr[1];
							}else
								txt = '';
						}
						signEdit.cssDisplay(1).find('input').val(txt);
					}).reg('signcl', function(e){
						signEdit.cssDisplay(0);
						signReal.cssDisplay(1)
					}).reg('signsa', function(e){
						var txt = Util.escapeHtml($.trim(signEdit.find('input').val()));
						if(Util.byteLen(txt)>100){
							Box.alert('','签名字数不能超过100个字符，50个汉字.')
							return;
						}
						e.lock(1)
						Req.setIntro(txt, function(r){
							e.lock(0)
							if(r.isOk()){
								signEdit.cssDisplay(0);
								if(txt == '') txt = '这个人很懒，还没有写签名';
								signReal.cssDisplay(1).find('span').text('“'+txt+'”');
							}else{
								Box.alert('',r.getMsg());
							}
						});						
					})
					
					signReal.closest('.user-intro').hover(function(e){
						signReal.find('.edit').cssDisplay(1);
					},function(e){
						signReal.find('.edit').cssDisplay(0);
					})
					//修改签名结束
					
					
					points = ui.jq('i.point'), addIcon.cssDisplay(0);
					v.hover(
						function(e){
							if(hover){
								addIcon.cssDisplay(1);
							}
						}
						,function(e){
							if(hover)
								addIcon.cssDisplay(0);
						})
					.mousemove(function(e){
						if(!hover) return;
						var addOffTop = e.clientY+$(document).scrollTop()-8, isF = true;
						
						for(var i=0,j=points.length;i<j;i++){
							var p = points.eq(i).offset().top;
							if(p+10>addOffTop && p-10<addOffTop){
								isF = false;
								break;
							}
						};
						addIcon.offset({ top:e.clientY+$(document).scrollTop()-8}).cssDisplay(isF);
					});
					
					addIcon.click(function(e){
						e.preventDefault();
						appendTo(addIcon.offset().top);
					});

					ui.jq('#addaJourney').click(function(e){
						e.preventDefault();
						var $t = $(this).closest('div.item');
						appendTo($t.offset().top, '', function(){
							$t.remove();
						});
					});
					$('#barAddJourney,#barAddJourney2').click(function(e){
						e.preventDefault();
						appendTo('', '');
					});
					
					
					function hoverOnItem(items){					
						items = items ? items : v.find('div.item');
						items.each(function(i){
							var $t = $(this), hi = $t.find('div.btn-action');
							$t.find('div.cont').unbind('hover').hover(function(){
								hi.cssDisplay(1);
							},function(){
								hi.cssDisplay(0);
							});
						})
					}
					
					hoverOnItem();
				}
				
				//隐藏旅途
				X.use('action').reg('hid', function(e){
					Box.anchorConfirm(e.src, '是否要隐藏该旅途?', function(btnId){
						if(btnId == 'ok'){
							Req.journeyUpdate(e.get('id'), 0, '', '', '','','','','', function(r){									
								if(r.isOk()){
									var oldItem = $(e.src).closest('.item');
									insertRule.del(oldItem);
									oldItem.remove();
								}else{
									Box.alert('', r.getMsg());
								}
							});							
						}
					});
				}).reg('ej', function(e){//编辑旅途
					var p = $(e.src).closest('div.item'), id = e.get('id'), d = cache[id];
					if(d) appendTo(p, d);				
				}).reg('del', function(e){
					$(e.src).closest('div.item').remove();
					Req.postReq(Req.jsAPI('journeyApi','setNotice'),{}, function(){});
				}).reg('addPic', function(e){
					var p = $(e.src).closest('div.item'), id = e.get('id'), d = cache[id];
					var area = {id:d.spot_id, name:Util.escapeHtml(d.spot_name)};
					X.use('JourneyImage', {
							area : area
							, areaName : area.name
							, selects : []
							, tab : e.get('t')||''
							, num : 0
							,editData : d
							, callBack : function(r){
								selectInsertItem(r);	
								cache[r.data.id] = r.data;	
							}
						}).display(1);		
				});
				
				
				function insert(id, beforeObj, opt, lastTime){
					var repeat = v.find('div.item[rel^="id:'+id+'"]');
					var $temp = $(T.parse(T.tpls.journeyItem, opt));
					if(!lastTime)
						$temp.css('opacity',0.1).insertBefore(beforeObj);
					else
						$temp.css('opacity',0.1).insertAfter(beforeObj);
					if(repeat.length){
						insertRule.del(repeat);
						repeat.remove();
					}					
					hoverOnItem($temp);
					$(document).scrollTop($temp.offset().top - 250);
					$temp.animate({ opacity:1} , 3000 );
					return $temp;
				}
				
				function selectInsertItem(reqData){//插入位置					
					var items = v.find('div.item'), len = points.length, json = reqData.data
					, has = false, newTime = Number(json.journey_time), newItem, hide = false, lastTime = false;
					if(newTime != '0'){//根据时间选出插入位置						
						var span = ui.jq('i.arrow'), noTime = false, insertObj;
						for(var i=0, len = span.length;i<len;i++){
							var time = Number(span.eq(i).attr('rel'));
							if(time && time !='0'){
								if(newTime>time){
									insertObj = span.eq(i);
									break;
								}
								noTime = span.eq(i);
							}
						}
						span = ui.jq('span.item-desc')
						var year = new Date(newTime*1000).getFullYear();
						for(var i=0, len = span.length;i<len;i++){
							if(span.eq(i).text() == year){
								hide = true;
								break;
							}
						}
						
						if(!insertObj && noTime !== false){
							insertObj = noTime;
							lastTime = true;
						}
						
						if(!insertObj) insertObj = items.eq(1);
						else
							insertObj = insertObj.closest('div.item');
							
						newItem = insert(json.id, insertObj, {newTime:newTime,content:reqData.html, hide:hide, time:year, id:json.id}, lastTime);

						hide && insertRule.add(newItem, year);
						
					}else{//未输入时间,插入到无时间区域 
						var span = ui.jq('span.item-desc');
						for(var i=0, len = span.length;i<len;i++){
							if(span.eq(i).text() == '某年'){
								hide = true;
								break;
							}
						}

						newItem = insert(json.id, ui.jq('#seeAll'), {newTime:0,content:reqData.html, hide:hide, time:'某年', id:json.id});							
					}
							
				}
				
				//年份显示处理
				var insertRule = {
					//add
					add : function (obj, year){
						var next = obj.next();
						var _year = next.find('span.item-desc').eq(0).text();
						if(_year == (year+'')){
							next.find('span.item-desc').text('');
							obj.find('span.item-desc').cssDisplay(1);
						}
					},
					
					//delete
					del : function(_obj){
						var item = _obj.find('span.item-desc');
						if(item.length){
							var _year = item.text();
							if(_year && _year != '某年'){
								var next = _obj.next();
								if(next.length && next.hasClass('item')){
									var yearString = next.find('i.arrow').attr('rel');
									if(yearString && yearString !='0'){
										var year = new Date(Number(yearString)*1000).getFullYear();
										if(year+'' == _year){
											next.find('i.point');
											if(next.find('span.item-desc').length == 0)
												$('<span class="item-desc">'+_year+'</span>').insertBefore(next.find('i.point'));
											else
												next.find('span.item-desc').text(year).cssDisplay(1);
										}
									}
								}
							}
						}
					}

				}
				
				
				//插入添加浮层
				function appendTo(atop, data, fn){
					hover = false;
					addIcon.cssDisplay(0);					
					addIcon.data({'cdata':data||'', 'atop':atop});
					var box = addIcon.data('box');
					if(box) box.display(1);
					else{
						box = Xwb.use('Layer', {
							view : $('#journeyForm')[0],
							appendTo : 'body',
							destroyOnClose : true,							
							mask : true,
							close : function(){
								this.display(0);
								this.aj.closeLayer();
							},
							onViewReady : function(){
								this.aj = X.use('AddJourney', {
									view : this.jq('#journeyCon')[0],
									parentUI : this,
									journeyInsert : function(reqData, status){
										this.cancel();
										if(status == 'edit'){
											var oldItem = addIcon.data('atop');
											insertRule.del(oldItem);
											oldItem.remove();
										}											
										selectInsertItem(reqData);	
										fn && fn();
										cache[reqData.data.id] = reqData.data;						
									},
									closeLayer : function(){
										box.display(0);
										hover = true;
										addIcon.cssDisplay(1);
									}
								}).display(1);
							},
							beforeShow : function(){
								X.ui.Layer.prototype.beforeShow.call(this);
								cdata = addIcon.data('cdata');
								atop = addIcon.data('atop');
								var top = $(document).scrollTop() +150;
								if(this._hidden){
									this._hidden = false;
								}else{
									if(cdata){						
										this.aj.initData.call(this.aj,cdata);
									}else{
										this.aj.status = 'add';									
										this.aj.reset();
									}
								}
								var wt = (Util.getClientHeight()-290)/2 + top - 150;
								$(this.view).css('opacity',0.1).offset({top:wt || (top<300?300:top)}).animate({ opacity:1} , 500 );
								$(this.view).find('#saveBtn').text(cdata?'保存':'添加');
								
							}
						}).display(1);
						addIcon.data('box', box);
					}
				}
				
			}
		})
		
		
		//旅途列表(去过，想去)
		var journeyList = Util.create(Pagelet,{
			onViewReady : function(cfg) {
				var _ui = this.getUI(), lis = _ui.jq('ul.list li');
				lis.each(function(i){
					var _t = $(this), h = _t.find('div.operate>div');
					$(this).hover(function(){
						h.cssDisplay(1);
					},function(){
						h.cssDisplay(0);
					})
				})
				
				X.use('ActionMgr', {target : _ui.view})
				.reg('del', function(e){
						var id = e.get('id');
						Box.anchorConfirm(e.src, '确定要删除旅途吗', function(btn){
							if(btn == 'ok'){
								Req.journeyDel(id,'', function(r){
									if(r.isOk()){
										//$(e.src).closest('li').remove();
										window.location.reload();
									}else{
										Box.alert('',r.getMsg());
									}
								});
							}
						});
				})
				.reg('hide', function(e){
						var id = e.get('id');
						Box.anchorConfirm(e.src,'确定要将该段旅程从旅途首页中隐藏?', function(btn){
							if(btn == 'ok'){
								Req.journeyUpdate(id, 0, '', '', '','','','','', function(r){									
									if(r.isOk()){
										var $t = $(e.src);
										$t.parent().find('span').remove();
										$t.replaceWith('<a rel="e:add" href="#"><i>+</i> 添加到我的旅途首页</a>');
									}else{
										Box.alert('', r.getMsg());
									}
								});
							}
						});
				})
				.reg('add', function(e){
					var hasArea = {}, id = e.get('id'), sid = e.get('sid'), $t = $(e.src);
					hasArea.id = sid;
					hasArea.name = e.get('n');
					var c = X.use('JourneyInfo', {
							appendTo : 'body',
							hasArea : {name:Util.escapeHtml(hasArea.name), id:hasArea.sid},
							closeable : true,
							mask : true,
							_title : '添加我的旅途',
							area : Util.escapeHtml(hasArea.name),
							destroyOnClose:true,
							cs : 'win-fixed win-journey-map win-journey-add',
							showTips : function(msg, obj){
								obj = obj ? obj : this.jq('#tips');
								obj.text(msg).cssDisplay(1);		
							},
							afterSelect : function(data){
								self.afterSelect.call(self, data);					
							},
							contentHtml : 'JourneyInfo',
							save : function(e){
								e.preventDefault();
								var data = this.getInfo(), self = this;
								if(data !== false){//保存旅程
									Req.journeyUpdate(id, 1, data.time[0], data.time[1], data.story,'','','',hasArea.name, function(r){									
										if(r.isOk()){
											self.close();				
											$t.parent().html('<a rel="e:hide" href="#"><i>x</i> 从我的旅途首页隐藏</a><br><a rel="e:del" href="#">删除</a>');
										}else{
											self.showTips.call(self, r.getMsg());
										}
									});
								}
							},
							onViewReady : function(){
								var self = this;
								X.ui.JourneyInfo.prototype.onViewReady.call(this);
							}
					})
					c.display(1);
				}).reg('delMark', function(e){
						var id = e.get('i');
						Box.anchorConfirm(e.src, getText('确定要删除该旅途?'), function(btn){
							if(btn == 'ok'){
								Req.delWantTo(id, function(r){									
									if(r.isOk()){
										window.location.reload();
									}else{
										Box.alert('', r.getMsg());
									}
								});
							}
						});
				}).reg('wt', function(e){
					e.stopPropagation(false);
				}).reg('gt', function(e){
					e.stopPropagation(false);
				})
			}
		});
		
		
		//旅途列表
		pipe.reg('journey.beenList',journeyList)
		pipe.reg('journey.wantToList',journeyList)
		
		//旅途地图
		.reg('journey.mine_map', {
			onViewReady : function(cfg) {
					var record = $('#record');
					var _ui = this.getUI(),
						data = cfg.data,
						foots = data.footmarks
						//,newFootmark = data.lastest;   
						
					//异步加载google map
					X.on('pipe.end', function(){
						window.baiduMap = baiduMap = {};
						X.use('LoadBaiduMap').initUI({view:_ui.getView(), canClickMark: true}, baiduMap, foots);
					});	
			
					X.on('footmark.updateCounter', function(nums){
						record.find('#wantToNum').text(nums[1]);
						record.find('#haveBeenNum').text(nums[2]);
						if(Number(nums[1])>=5 && Number(nums[2])>=5){
							_ui.jq('#fpMedal').slideDown('slow',function(e){
								$(this).remove();
							})
						}
							
					});
					
					X.cfg.mymap = true;
			}
		})
		
		.reg('journey.ta_map', {
			onViewReady : function(cfg) {
					var record = $('#record');
					var _ui = this.getUI(),
						data = cfg.data,
						foots = data.footmarks
						//,newFootmark = data.lastest;   
						
					//异步加载google map
					X.on('pipe.end', function(){
						window.baiduMap = baiduMap = {};
						X.use('LoadBaiduMap').initUI({
							view:_ui.getView()
							, canClick : false
							, canClickMark: true
							, rightLists : false
							, noAbroad : true							
							}, baiduMap, foots);
					});	
			
					X.on('footmark.updateCounter', function(nums){						
						record.find('#wantToNum').text(nums[1]);
						record.find('#haveBeenNum').text(nums[2]);
						if(Number(nums[1])>=5 && Number(nums[2])>=5){
							_ui.jq('#fpMedal').slideDown('slow',function(e){
								$(this).remove();
							})
						}
							
					});
					
					X.cfg.mymap = false;
					$('#gmap').parent().css('width','100%')
			}
		})
		
		//明信片评论
		.reg('postcard.commentBox', {
			onViewReady : function(cfg) {
				pid = pid || 15;
				var data = cfg.data,
					ui = this.getUI();
				var cmt = X.use('CmtArea', {
					wbId : pid,
					wbUid : pid,
					newSystem : true,
					profileImg : getCfg('face_m') || '/img/default.png',
					appendTo: ui.jq(),
					type : 'postcart',
					maxLen: 140*2,
					localComments :true,
					getCommentUrl : Req.getPostCardList,
					commentUrl : Req.postCardComment,
					replyUrl : Req.postCardReply,
					delComment:function(){
						Req.delPostCardCmt.apply(Req,arguments);
					},
					afterShow : function() {
						//检测url Hash ，如果是comment，则focus到输入框
						if (location.hash == '#comment') {
							$(document).scrollTop(this.jq().offset().top-75);
							this.jq('textarea').focus();
						}
					}
				});
				cmt.display(1);
				cmt.load();

				X.cfg.cmt = cmt;
				//读取发表成功加分提醒					
				Req.getRemindStatus({type:'yj.new'},function(e){
					if(e.isOk()){
						var str = e.getData();
						if(str) 
							X.use('CoinExperience',{notice :str});
							//Box.extTip('<div class="win-success win-fixed">'+str+'</div>','');
					}
				});
				
				
				var open = $('#lookPro'), close = $('#hidePro'), con = $('#lookContent');
				close.click(function(e){
					e.preventDefault();
					close.cssDisplay(0);
					open.cssDisplay(1);
					con.cssDisplay(0);
				});
				open.click(function(e){
					e.preventDefault();
					open.cssDisplay(0);
					close.cssDisplay(1);
					con.cssDisplay(1);
				});
			}			
		})
		
		//制件明信片(右边选择模\贴邮票)
		.reg('postcard.tplList', {
			onViewReady : function(cfg){
				var cd = cfg.data, switcher = $('#switcher'), conts = switcher.find('div.cont'), spans = switcher.find('#sLabel>span')
				, oid = cd.id //原始选择
				, types = 'm_'+(cd.type||1)
				, mData = {} //模板数据集
				, pageSize = 8
				, isSave = false
				, curData1 = ''//当前数据列表
				, curData2 = ''//当前数据列表
				, curData3 = ''//当前数据列表
				, noData1 = '呃，没有找到模板'
				, noData2 = '呃，没有找到邮票'
				, noData3 = '呃，没有找到匹配邮戳~只能盖一个通用版邮戳啦。'
				, ie = !$.browser.mozilla
				, curType = 1//当前分类
				, tpcInit = false;//贴邮票初始化
				mData[types] = cd.list;
				var sw = X.use('Switcher', {
					items : spans,
					contents : conts,
					selectedCS : 'curr',
					onselect : function(dom){
						var $dom = $(dom), type = Util.parseKnV($dom.find('a').attr('rel')).type;
						curType = type;
						if(type == 2 && !tpcInit){//未初始化贴邮票
							tpcInit = true;
							getData(Req.getTpcList, {page:1}, selTpc);
						}
						if(type == 3){
							initYou();
						}
						
					}
				});
				
				window.onbeforeunload =  function(e){
					if(!isSave)
						return '未保存内容,确定要离开吗?';
				}
				
				function initPage(count, curPage, pageSize, view, loadData){
					pageSize = 8;
					var sh = count == 0? 0:(count/pageSize>1?1:0);
					var page = X.use('SimplePage', {
						view : view,
						count : count,
						loadData : loadData||'',
						curPage : curPage,
						pageSize : pageSize || 8
					}).display(sh)
					
					return page; 
				}
				
				//处理flash中文输入问题,在ie下用window模板渲染flash弹出浮层有问题
				function setFlashBoxByIe( msg, buttons, icon, callback){
					var w = Box.getSysBox({frameMask: true
					,buttons : [{title: getText('确&nbsp;定'),     id :'ok', cs:'btn-s1'}]
					}), btns = w.buttons;
						if(!buttons)
							def = buttons = 'ok';
						if(!icon)
							icon = 'alert';
						//for(var i=0,len=btns.length;i<len;i++){
						//	w.jq('#xwb_btn_'+btns[i].id).cssDisplay(buttons.indexOf( btns[i].id ) >= 0);
						//}
						w.defBtn = def;
						w.setTitle('提示');
						msg   && w.setContent(msg);
						icon  && w.setIcon(icon);
						callback && (w.onbuttonclick = callback);
						w.display(true);
						$(w.frameMaskEl).css('opacity',0.5);
				}				
				
				function createHtml(parent, data, templ, type){
					if(curType == 1) curData1 = data;
					else if(curType == 2) curData2 = data;
					else curData3 = data;
					var len = data.length, htmls = [];
					if(len){
						for(var i=0;i<len;i++){
							htmls.push(T.parse(templ, data[i]));
						}
						parent.html(htmls.join(''));
					}else{
						var li = '';
						if(type == 3){
							li = '<li><div class="tpl"><a href="#" rel="e:steml,id:0"><img src="/img/postcard/postmark/s1.png"><span></span></a></div></li>';
						}
						parent.html('<div class="tips-null-s2"><span class="ico-alert"></span><p>'+(type == 1?noData1:(type == 2?noData2:noData3))+'</p></div>'+li );
					}
					parent.children().hover(function(){
						$(this).find('div.tpl').addClass('hover');
					},function(){
						if($(this).find('span.select').length == 0 ) $(this).find('div.tpl').removeClass('hover');
					});					
				}
				
				//选出对应的数据在哪一页,如果id为空就用page定位
				function selectData(data, id, pageSize, page){
					pageSize = 8;
					var len = data.length, tempData = [], has = false, tempPage = 1;
					if(len<pageSize) return [data,tempPage];
					if(id){
						for(var i=0;i<len;i++){
							tempData.push(data[i]);
							if(id == data[i].id){
								has = true;
							}
							if((i+1)%pageSize == 0 && !has && (i+1)<len){
								tempPage ++;
								tempData = [];
							}
							if((i+1)%pageSize == 0 && has){
								break;
							}
						}
					}else{
						page = page ? page:1;
						if(page>len/pageSize) return [data,1];
						for(var i=0;i<len;i++){
							tempData.push(data[i]);
							if((i+1)/pageSize == page){
								break;
							}
							if((i+1)%pageSize == 0){
								tempPage ++;
								tempData = [];
							}
						}
					}
					return [tempData, tempPage];
				};
				
				function setSelectedCs(parent, id){
					var li = parent.find('li[rel='+id+']');
					li.find('span').addClass('select');					
					li.find('div').addClass('hover');
				}
				
				function getData(R, data, fn){
					R.call(Req, data, function(r){
						fn(r);
					})
				}
				//删除所有选中
				function cancelSelect(){
					switcher.find('span.select').each(function(){						
						$(this).removeClass('select').closest('div.tpl').removeClass('hover');;
					})
				}
				
				
				var templ = '<li rel="{.id}"><div class="tpl"><a href="#" rel="e:steml,id:{.id}"><img src="{.pic}{.thumb_pic}{.postmark}" title="{.name}"><span></span></a></div></li>';
				var d = selectData(cd.list, cd.id, 1), ul = conts.eq(0).find('ul:eq(0)');
				createHtml(ul, d[0], templ, 1);
				setSelectedCs(ul, cd.id||1);
				var pageUI = initPage(cd.list.length, d[1], 8, conts.eq(0).find('#page')[0], function(p, fn){
					var tempd = selectData(cd.list, '', 1, p);
					createHtml(ul, tempd[0], templ, 1);
					fn.call(this);
				});
				X.use('action').reg('sl',function(e){					
					var _t = $(e.src), type = 'm_'+e.get('t'), d = mData[type];
					if(_t.hasClass('cur')) return;
					
					function set(_r, _tempd){						
						createHtml(ul, _tempd[0], templ, 1);
						pageUI.reset(_r.length, 1, 8);
					}					
					if(d){
						var tempd = selectData(d, '', 1, 1);							
						set(d, tempd);
					}else{
						ul.html('<div class="loading"></div>');
						getData(Req.getTplList, {type:e.get('t') }, function(r){
							if(r.isOk()){
								d = r.getData();
								mData[type] = d.list;		
								var tempd = selectData(d.list, '', 1, 1);							
								set(d.list, tempd);
							}
						});
					}
					
					_t.parent().find('.cur').removeClass();
					_t.addClass('cur');
				}).reg('steml', function(e){ //选择
					var id = e.get('id'), $t = $(e.src);
					if($t.find('.select').length) return;		
					//if(Number(curType) == 1){
					//	cancelSelect();
					//}else{
						var ul = $t.closest('ul'), select = ul.find('span.select');
						select.removeClass('select');
						select.closest('div.tpl').removeClass('hover');
					//}
					$t.find('span').addClass('select');					
					switch(Number(curType)){
						case 1 : 
							var flashData = formatData(id, curType);
							thisMovie('Card').flashFunc('data', flashData);
						break;
						case 2 : 
							tpcSid = id;
							letter(getDataById(id, curType));
						break;
						case 3 : 
							youid = id;
							postmark(getDataById(id, curType));
						break;
					}
				}).reg('preview', function(e){ //预览
					var cardFlash = thisMovie('Card'), $e = $(e.src), box = $e.data('box');
					if(!cardFlash.flashFunc('is_upload')){
						if(ie) setFlashBoxByIe('你还没有上传自己的照片');
						else Box.alert('','你还没有上传自己的照片');
						return;
					}
					var imgObj = cardFlash.flashFunc('preview');
					function _thisMovie(movieName) {
						if(navigator.appName.indexOf("Microsoft") != -1) {
							return window[movieName];
						} else {
							return document[movieName];
						}
					};
					window.previewjsFunc = function(param){
						if(param == 'loadComplete'){
							_thisMovie('imgBox').flashFunc('imgByteStr', imgObj)
						}
					}
					if(!box){
						box = X.use('Box',{
							cs : 'win-card-preview win-fixed',
							contentHtml : '<div id="imgBox"></div>',
							appendTo : document.body,
							frameMask : ie,
							title: '预览明信片',
							closeable : true,
							mask: true,
							onViewReady : function(){
								var self = this;
								var flashvars={
										flashFunc:'flashFunc',
										jsFunc:'previewjsFunc'
									};
								var params = {
										AllowScriptAccess:"sameDomain",
										wmode:"transparent"
									};
								swfobject.embedSWF("/flash/ImgBox.swf?v="+getCfg('subver'), "imgBox", "600", "400", "10.0.0", "expressInstall.swf",flashvars,params);									
							},
							breforeShow : function(){
								X.ui.Box.prototype.breforeShow.call(this);								
							}
						}).display(1);
						$e.data('box', box);						
					}else{
						box.display(1);
						setTimeout(function(){_thisMovie('imgBox').flashFunc('imgByteStr', imgObj)},500);						
					}
				})
				
				.reg('next', function(e){//先检查数据，再提交
					if(saveLock) return;
					var cardFlash = thisMovie('Card');
					//e.lock(1);				
					if(cardFlash.flashFunc('is_upload')){														
							function continueNext(content){
								if(cardFlash.flashFunc('is_setPostmark')){
									saveLock = true;
									cardFlash.flashFunc('save','{"rst":"'+content+'","errno":"","err":""}');
								}else{
									var dlg = Xwb.use('Dlg', {
										appendTo:'body',
										title:'提示',
										frameMask : ie,
										dlgContentHtml : 'MsgDlgContent',
										mask : true,
										onViewReady : function(){
											this.jq('#xwb_msgdlg_ct').html('你未选择添加邮戳，是否返回添加？');										
										},
										onbuttonclick : function(eid){
											if(eid == 'ok'){
												saveLock = true;
												cardFlash.flashFunc('save','{"rst":"'+content+'","errno":"","err":""}');
											}
											//e.lock(0);
										},
										buttons : [
										  {title:'不添加了',     id :'ok', cs:'btn-s1'},
										  {title: '返回添加',     id :'cancel', cs:'btn-s1 btn-s1-gray'}
										]}).display(1);
								}
							}
							
							var txt = cardFlash.flashFunc('getInputText');
							if(txt){
								Req.filterKeyword(txt, function(r){
									if(r.isOk()){
										continueNext(r.getData().content);
									}
								});
							}else{
								continueNext('');
							}
					}else{
						e.lock(0);
						if(ie) setFlashBoxByIe('你还没有上传自己的照片，无法继续哦');
						else Box.alert('','你还没有上传自己的照片，无法继续哦');
					}
					//new Req.DefaultResponseDefinition( $.parseJSON(json) );
				});
				
				function getDataById(id, type){
					var _curData = type==1?curData1:(type == 2?curData2 :curData3)
					for(var i=0;i<_curData.length;i++){
						if(id == _curData[i].id){
							if(type == '1'){
								return _curData[i];
							}
							return $.toJSON( _curData[i]);
						}
					}
					
					if(type == 3 && id == '0'){						
						return $.toJSON({id:'',name:$.trim(conts.find('#areaInpt').val()),postmark:'/img/postcard/postmark/s1.png'});
					}
				}
				
				//邮票
				var tpc = conts.eq(1), tpcUl = tpc.find('ul:eq(0)');
				var tpcPageUI = '', tpcSid = '';
				function selTpc(r){
					if(r.isOk){
						var d = r.getData();
						createHtml(tpcUl, d.list, templ, 2);
						if(tpcSid){
							setSelectedCs(tpcUl,tpcSid);
						}
						if(d.total_number/6>1)
						tpcPageUI = initPage(d.total_number, 1, 6, tpc.find('#page')[0], function(p, fn){
										var self = this;
										getData(Req.getTpcList, {page:p}, function(rr){
											if(rr.isOk()){
												tpcUl.html('<div class="loading"></div>');
												createHtml(tpcUl, rr.getData().list, templ, 2);
												fn.call(self);
											}
										});
									});
					}
				}
				
				//盖邮戳
				var you = conts.eq(2), youUl = you.find('ul:eq(0)'), youid;
				function initYou(){
					var $search_bar = you.find('#searchArea'), $areaInpt = you.find('#areaInpt'), req = '';
					if(!$search_bar.data('init')){
						$search_bar.data('init',true);
						var delayTime = 200;
						$areaInpt.click(function(){
							var v = Util.trim(this.value);
							if(v == '搜景点') this.value = '';
						}).keyup(function(e){
								//var self = this;
								//setTimeout(function(){
									var v = Util.trim(this.value);
									if(v != ''){
										req = getDefaultCardYou(v);
									}else{
										//if(req == '')
											req = getDefaultCardYou('');
									}									
								//}, delayTime);
						});
						req = getDefaultCardYou('');//首次进来出默认
					}					
					function getDefaultCardYou(v){
						return Req.postCardYoSearch({k:v}, function(r){
							req = '';
							if(r.isOk()){												
								createHtml(youUl, r.getData().spots, templ, 3);
								if(youid){
									setSelectedCs(youUl,youid);
								}
							}
						})
					}
				}
				
				
				var saveLock = false; //save保存锁定
				//flash
				window.flashToJsFunc = function(type,data){   
					if(type == 'letter'){
						tpcSid = data.property.id;
						sw.select(spans.eq(1)[0]);
					}else if(type == 'postmark'){		
						sw.select(spans.eq(2)[0]);
					}else if(type == 'fto_error'){
						//var e = new Req.DefaultResponseDefinition($.parseJSON(data));
						if(ie) setFlashBoxByIe(data.err);
						else Box.alert('',data.err);						
					}else if(type == 'success'){
						saveLock = false;
						var e = new Req.DefaultResponseDefinition($.parseJSON(data));
						if(e.isOk()){
							isSave = true;
							window.location.href = e.getData().url;
						}else{
							if(ie) setFlashBoxByIe(e.getMsg());
							else Box.alert('',e.getMsg());
							//Box.alert('',e.getMsg());
						}
					}else{
						sw.select(spans.eq(0)[0]);
					}
				}   
				function letter(data){
					thisMovie('Card').flashFunc('letter',data);
				}
				 
				function postmark(data){
					thisMovie('Card').flashFunc('postmark',data);
				}
				function thisMovie(movieName) {
					if(navigator.appName.indexOf("Microsoft") != -1) {
						return window[movieName];
					} else {
						return document[movieName];
					}
				};
				
				
				function formatData(id){
					var d = getDataById(id, 1);
					for(var i=0;i<d.elements.length;i++){
						if(typeof d.elements[i].property == 'string')
							d.elements[i].property = eval('('+d.elements[i].property+')');
					}
					return $.toJSON(d);
				}
				
				var flashData = formatData(cd.id);
				
				var flashvars={
						flashFunc:'flashFunc',
						jsFunc:'flashToJsFunc',
						data:escape(flashData),
						upload_url:escape(Req.jsAPI('postcardApi','upload')),
						_PHPSESSID:$('#_PHPSESSID').val(),
						fontLib:escape('/flash/fontLib.swf?v=' + X.getCfg('subver')),
						default_pic:escape('/img/postcard/default.png'),
						save_url:escape(Req.jsAPI('postcardApi','save'))
					};
				var attributes = {
					id: "Card",
					name: "Card"
				};
				var params = {
							AllowScriptAccess:"sameDomain",
							wmode: ie ? 'window' : 'opaque' 
							};
				swfobject.embedSWF("/flash/Card.swf?v="+getCfg('subver'), "Card", "600", "400", "10.0.0", "expressInstall.swf",flashvars,params,attributes);
			}
		})

		
		
		
		//码头动态
		.reg('center.dynamic_tab', {
			onViewReady : function(){
				var ui = this.getUI();
				ui.jq('#btn_sign').click(function(){
					var self = this;
					if(self.getAttribute('lock'))
						return ;
					self.setAttribute('lock','1');
					Req.jsApiCall('signApi','checkIn',{}, function(rst){
						if(rst.isOk()){
							var $signTip = $('<div id="signTip" class="sign-score" style="top:0px">+500游币</div>');
							self.className = 'signed';
							$signTip.insertAfter( $(self.parentNode.parentNode) )
									.animate({opacity:0,top:-60},1200);
							$(self).unbind('click');
						}else 
							Box.alert('提示',rst.getMsg());
						self.removeAttribute('lock');
					});
					return false;
				});
				ui.jq('#btn_newTopic').click(function onesFn(){
					var n = pipe.getByType('center.nav').joinedGroupCount;
					if( n == 0 ){
						var gl = X.use('groupLayer');
						gl.display(1);
						gl.jq('#nullTip').removeClass('hidden');
						return false;
					}
				})
			}
		})
		.reg('center.dynamic', {
			onViewReady : function( cfg ){
				var ui = this.getUI();
				this.url = cfg.data.url;
				
				this.tipsFeedData = [];   //统计帖子数据
				
				this.statTipsFeedData( cfg.data.feed );  // 统计帖子的数据
				
				this.getTipsCount( this.tipsFeedData );
				
				if( !cfg.data.has_next )
					return ;
				var self = this,
					lock = false;
				$(window).bind('scroll',function(){
					if( $(document).scrollTop() + Util.getClientHeight() > $(document.body).height() - 50 ){
						if( lock )
							return false;
						lock = true;
						self.showLoading();
						Req.postReq( self.url, {}, function(r){
							if(r.isOk()){
								var rstData = r.getData();
								self.url = rstData.url;
								if( rstData.html ){
									$(ui.view).append(rstData.html);
									
									self.getTipsCount( self.statTipsFeedData() );
								}
								if( !rstData.has_next ){
									$(window).unbind('scroll');
									delete self;
								}
							}
							else Box.alert('提示',r.getMsg())
							
							self.hideLoading();
							lock = false;
						})
					}
				});
			},
			statTipsFeedData : function( feedData ){
				var arr = [];
				for(var i in feedData){
					if( feedData[i].data.tie_id )
						arr.push( feedData[i].data.tie_id );
				}
				this.tipsFeedData = arr;
				return arr;
			},
			getTipsCount : function( ties ){   //获取tips评论数
				if( ties.length > 0 )
					ties = ties.join(',');
				else if( !ties )
					return ;
				
				Req.getTipsCount( ties, function(e){
					if(e.isOk()){
						var data = e.getData();
						if(data && data.tie){
							var tie = data.tie
							var len = tie.length;
							for(var i=0;i<len;i++){
								var tieItem = tie[i],
									countView = $("#tie_id_"+tieItem.id);
								countView.children('a').eq(0).html('浏览(<b>'+tieItem.view+'</b>)')
								countView.children('a').eq(1).html('评论(<b>'+tieItem.comment+'</b>)')
							}
						}	
					}
				});
			},
			showLoading : function() {
                $(this.getUI().getView()).parent().append('<div id="_loadingTip" class="loading"></div>');             
            },
            hideLoading : function() {
                $('#_loadingTip').remove();
            }
		})
		//小组浮层
		.reg('center.nav', {
			onViewReady : function(cfg){
				cfg = cfg || {};
				var g_count = 0; //统计已加入小组
				for(var k in cfg.data) 
					g_count++;
				this.joinedGroupCount = g_count;
				var self = this;
				X.on('countJoinedGroup',function(n){
					self.joinedGroupCount += n;
				});
				
				$('span.js_btn_plus').click(function(){
					if( X.getUid() ){
						X.use('groupLayer').display(1);
						$('#emptyTip').remove();
					}else Xwb.use('loginBox').display(1);
				});
			}
		});
		
		//我的印象、推荐印象pagelet基类
		var ImpressPletBase = Util.create(Pagelet,{
			insertTag : 'div.col',
			onViewReady : function( cfg ){
				var ui = this.getUI(),
					data = cfg.data.data || cfg.data.list;   //印象数据
				this.url = cfg.data.url;
				this._data = cfg.data;//备份数据
				if( !data || !data.length ) {
					!this.album && (ui.jq().append($(T.parse('impressNullTip'))));
					return ;
				}
				this.data = data;
				this.$cols = ui.jq(this.insertTag);
				
				this.regAction();
				this.insert( this.data );

				if( this.makeUrl || this.url )
					this.setScroll();
			},
			/** 
			 * 接口方法 regAction. 注册内部action
			 */
			regAction : function(){},
			/**
			 * 接口方法 ItemViewSetting. 每一项印象的视图
			 */
			ItemViewSetting: function( jqColBox, itemHtml ){
				jqColBox.append($(itemHtml));
			},
            
			insert : function( data ){
				var imgHeightArr = [],
					len = data.length,
					sum = 0;    //这一批印象条目所包含图片的高度的总和
				if( len < 1 ) return ;
				for(var i=0;i<len;i++){
					var ih = data[i].img_height, 
						iw = data[i].img_width,
						addsHeight = 106;   //附加高度,包括边距,填充...
					if( iw )
						ih = ih*(280/iw);  //固定官渡
					
					imgHeightArr[i] = ih + addsHeight;
					sum += imgHeightArr[i];
				}
									
				var $cols = this.$cols,
				    rest = $cols.eq(0).height() - $cols.eq(1).height(),  //当前两列的差值
					tarHeight = (sum - Math.abs(rest))/2,  //较高的那一列，应填充的高度
					subset = Util.subsetSplit(imgHeightArr, tarHeight);   //具体查看subsetSplit的返回
				
				var shorter = 0, higher = 1;
				if( rest > 0 ) {
					shorter = 1;
					higher = 0;
				}
				for(var i=0;i<len;i++){
					if( subset[i] == 1 )
						this.ItemViewSetting( $cols.eq(higher), data[i].html )
					else 
						this.ItemViewSetting( $cols.eq(shorter), data[i].html )
				}
			},
			setScroll: function(){
				var self = this,
					lock = false;
				$(window).bind('scroll',function(){
					if( $(document).scrollTop() + Util.getClientHeight() > $(document.body).height() - 50 ){
						if( lock )	
							return false;
						lock = true;
						self.showLoading()
						Req.postReq( self.url, {}, function(r){
							if(r.isOk()){
								var rstData = r.getData();
								rstData.url ? self.url = rstData.url : $(window).unbind('scroll');
								self.insert( rstData.data );
							}
							else Box.alert('提示',r.getMsg())
							self.hideLoading();
							lock = false;
						})
					}
				});
			},
			showLoading : function() {
                $(this.getUI().getView()).parent().append('<div id="_loadingTip" class="loading"></div>');             
            },
            hideLoading : function() {
                $('#_loadingTip').remove();
            }
		});
		
		//印象页的action，统一放到该方法里面注册
		function regImpressPageAction(){
			X.use('action')
			.reg('del',function(e){
				Box.anchorConfirm(e.src,'确定要删除该印象吗?',function(id){
					if('ok' === id)
						Req.jsApiCall('center','impress_delete',{ id: e.get('rid')},function(r){
							if(r.isOk()){
								$(e.src.parentNode).remove();
							}else Box.alert('',r.getMsg());
						},'POST');
				})
			})
			.reg('edit',function(e){
				var $src = $(e.src),
					type = e.data.type,
					text = $src.parent().prev('input').val(),
					warnInfo = {
						exp: [50, '感受不能为空或超过50个字'],
						tag: [12, '感受不能为空或超过12个字']
					};
				
				if( !$.trim(text) || text.length > warnInfo[type][0] )
					return Box.alert('',warnInfo[type][1]);
				var m = (type == 'exp' ? 'set_exp' : 'set_tag');
				
				text = Util.escapeHtml(text);   //过滤一下
				Req.jsApiCall('center',m,{ tag: text, exp: text, img_id: e.get('id')},function(r){
					if(r.isOk()){
						var $editArea = $src.closest('form'),
							$infoBox = $editArea.parent().prev(),
							$info = $infoBox.find('#'+type);
						$info.attr('editedText',text).html(text+'<b class="ico-edit"></b>');
						$infoBox.removeClass('hidden');
						$editArea.parent().remove();
					}else Box.alert('',r.getMsg());
				},'POST')

			})
			.reg('cancel',function(e){
				var $editArea = $(e.src).closest('form');

				var $divRow = $editArea.parent();
				$divRow.prev().removeClass('hidden');
				$divRow.remove();
			});
		}
		
		pipe
		//推荐印象
		.reg('center.impress',ImpressPletBase)
		//我的印象
		.reg('center.my_impress',function(){ 
			return new ImpressPletBase({
				regAction : function(){
					regImpressPageAction();  //注册action
				},
				ItemViewSetting: function( jqColBox, itemHtml ){
					var self = this;
						$item = $(itemHtml);
					$item.css('opacity',0)
						.hover(
							function(){ $(this).find('a.btn-close').removeClass('hidden');},
							function(){$(this).find('a.btn-close').addClass('hidden');}
						);
					$item.find('div.area')
						.delegate('div.row>span','hover', function(){
							$(this).toggleClass('hover');
						})
						.find('span.desc').click(modify);
					function modify(e){
						var type = this.id || 'exp',  // 'exp' | 'tag'
						    editedText = '';
							
						$(this).parent().addClass('hidden');
						if( $(this).attr('editedText') )
							editedText = $(this).attr('editedText');
						var $EidtArea = $(self.createEidtArea( { editedText: editedText, type: type } ));
						$EidtArea = $('<div class="row"></div>').append($EidtArea);
						$EidtArea.insertAfter( $(this).parent() );

						Util.focusEnd( $EidtArea.find('input')[0] );
					}
					
					$item.find('span.tags').click(modify)
					jqColBox.append($item);

					$item.animate( {'opacity':1}, 1200 );
				},
				createEidtArea : function( tpl ){
					return T.parse('impressEdit',tpl);
				}
			})
		})
		//单个印象详细页
		.reg('center.detail', {
			onViewReady : function( cfg ){
				var ui = this.getUI(),
					self = this;
					
				function modify(e){
					var type = this.id || 'exp',  // 'exp' | 'tag'
						editedText = '';
						
					$(this).parent().addClass('hidden');
					if( $(this).attr('editedText') )
						editedText = $(this).attr('editedText');
					var $EidtArea = $(self.createEidtArea( { editedText: editedText, type: type } ));

					$EidtArea = $('<div class="row"></div>').append($EidtArea);
					$EidtArea.insertAfter( $(this).parent() );

					Util.focusEnd( $EidtArea.find('input')[0] );
				}
				ui.jq('#exp').click(modify);
				ui.jq('#tag').click(modify)
				regImpressPageAction();  //注册action
			},
			createEidtArea : function( tpl ){
				return T.parse('impressEdit',tpl);
			}
		})
		//单个印象页的评论
		.reg('center.comment',{
			onViewReady : function(cfg) {
				var ui = this.getUI(),
					img_id = cfg.data.img_id,
					yj_id = cfg.data.youji.id;
				var cmt = X.use('CmtArea', {
					wbId :  img_id,   //获取评论的ID
					newSystem : true,
					profileImg : getCfg('face_m') || '/img/default.png',
					appendTo: ui.jq(),
					trigEl : '#b_comment',
					type : 'impress',
					maxLen: 200*2,
					showEmotion : false,
					commentHtml : 'ImpressComment',
					commentUrl : function(id, text, forward, hpt, fn, cfg){	
						Req.act('commentsApi', 'comment', {
							id: yj_id,
							text:text,
							forward : forward,
							pid : img_id,
							type:hpt
						   }, fn, cfg
						);
					},
					replyUrl :  function(id, cid, text, forward, hpt, fn, cfg){
						cfg = cfg?cfg:{};
						Req.postReq(Req.jsAPI('commentsApi','reply'), {
							id: yj_id,   //
							cid: cid,
							text:text,
							forward : forward,
							type:hpt
						   }, fn, cfg
						);
					},
					localComments :  true,

					getCommentUrl : Req.getImageComments,
					onViewReady : function() {
						var focusCS = 'style-focus';
						this.jq('textarea').bind({
							focus: function(){
								$(this).addClass(focusCS)
							},
							blur : function(){
								$(this).removeClass(focusCS);
							}
						})
					}
				});
				cmt.display(1);
				cmt.load();
			}
		})
		
		
		//旅途右边栏
		.reg('center.spots_fav', {
			onViewReady : function(){
				var ui = this.getUI(),
					self = this;
				
				self.tripControl = X.use('manageTrip',{
					addCallback: function( spotData ){
						ui.jq('#trip_nullTip').remove();
						var $tripBox = this.jqView;
						$tripBox.find( '#t'+ spotData.id +':checkbox' ).attr('checked', true).parent('label').addClass('selected');
						
						$tripBox.find('ul.selected-list').append( T.parse('spotsItem', spotData ) );
						
						ui.jq('ul.trip-tags').append('<li id="trip_tags_'+spotData.id+'"><a href="#">'+spotData.name+'</a><span rel="e:delSpot2,id:'+spotData.id+'"></span></li>');
					},
					delCallback : function( spotData ){
						var $tripBox = this.jqView;
						$tripBox.find( '#t'+ spotData.id +':checkbox' ).attr('checked', false).parent('label').removeClass('selected');
						$tripBox.find( '#li_'+spotData.id ).remove();
						
						ui.jq('ul.trip-tags #trip_tags_'+ spotData.id).remove();
					}
				})
				
				ui.jq('#btn_tripPlus1,#btn_tripPlus2').click(function(){
					X.getUid() ?  self.tripControl.display(1) : X.use('loginBox').display(1);
					return false;
				});

				ui.jq('ul.trip-tags')
				.delegate('li','mouseover',function(){
					this.className = 'active';
				})
				.delegate('li','mouseout',function(){
					this.className = '';
				});
					
				X.use('action').reg('delSpot2',function(e){
					var spotData = {
						id : e.data.id,
						name : $(e.src).prev('a').html()
					}
					var tc = self.tripControl;
					if( tc.innerControl ){
						tc.innerControl.reqSetSpot( 'del', spotData, function(){ $(e.src).parent().remove(); } );
					}
					else {
						Req.jsApiCall('center','guide_fav_del', spotData, function(rst){
							if(rst.isOk()){
								$(e.src).parent().remove();
							}else Box.alert('提示',rst.getMsg());
						})
					}
				})
			}
		})
		
		//小组详细页
		.reg('group.detail_tab',{
			onViewReady : function(){
				var ui = this.getUI();
				ui.jq('#btn_pubTopic').click(function f(){
					var $btn_join = $('#btn_join');
					if( !Xwb.getUid() ){
						$btn_join.click();  //触发弹出登录浮层
						return false;
					}
					/*未加入小组的判断,因为该需求是后加的,根据html结构判断*/
					if( $btn_join[0] && !$btn_join.hasClass('hidden') ){  
						Box.confirm('','您还不是该小组成员，是否马上加入该小组?',function(btn_id){
							if(btn_id == 'ok'){
								var relData = Util.parseKnV( $btn_join.attr('rel') );
								gid = relData.id || 0;
								Req.jsApiCall('groupApi','join_group',{gid: gid}, function(rst){
									if( rst.isOk() ){
										location.href = $('#btn_pubTopic')[0].href;
									}else Box.alert('提示',rst.getMsg());
								},'POST');
							}
						})
						return false;
					}
				})
			}
		})
		.reg('group.detail_topiclist', pipe.pages['group.detail_tab'] )
		
		//小组帖子页的评论
		.reg('group.topic_comment',{
			onViewReady : function(cfg) {
				if( /#npt$/.test(location.href) ){
					setTimeout( function(){
						X.use('CoinExperience',{notice : "发表成功！自游币 +300 经验 +30"});
					    location.href = location.href.replace('#npt','#');  //去掉#npt(new post topic)的hash标识
					},1000);
				}
				
				var data = cfg.data,
					ui = this.getUI(),
					delRigth = data.user_state.utype > 0 ? true : false;
					
				var cmt = X.use('CmtArea', {
					wbId :  data.id,
					newSystem : true,
					profileImg : getCfg('face_m') || '/img/default.png',
					appendTo: ui.jq(),
					trigEl : '#b_comment',
					type : 'topic',
					maxLen: 140*2,
					commentHtml : 'TopicComment',
					localComments :  true,
					getCommentUrl : Req.getTopicComments,
					commentUrl : Req.topicComment,
					replyUrl : Req.topicReply,
					delComment: Req.topicDelComment,
					
					onViewReady : function() {
						var cmt = this;				
						if( /#comment$/.test(location.href) ){
							//焦点位置
							$(document).scrollTop(cmt.cmtBox.jqInputor.offset().top);
							cmt.cmtBox.jqInputor.focus();	
						}
						var focusCS = 'style-focus';
						
						this.isGroupAdmin = delRigth;   //管理员
						
						this.jq('textarea').bind({
							focus: function(){
								$(this).addClass(focusCS)
							},
							blur : function(){
								$(this).removeClass(focusCS);
							}
						});
						
						if( Xwb.getUid() ){   //已登录
							this.jq('#cmtBox a.btn-s4').click(function oneFn(e){
								var $this = $(this),
									$btn = $('#joinGroup'),
									v = $('#cmtBox #inputor').val();

								if( $.trim(v) != '' && !$btn.hasClass('hidden') ){
									Box.confirm('','您还不是该小组成员，是否马上加入该小组?',function(btn_id){
										if(btn_id == 'ok'){
											var gid = $('#joinGroup').attr('rel').split(',');
											gid = gid[2].split(':')[1];
											Req.jsApiCall('groupApi','join_group',{gid: gid}, function(rst){
												if( rst.isOk() ){
													$this.unbind('click', oneFn);
													setTimeout(function(){
														$this.click();
													},100);
													$('#joinGroup').addClass('hidden');
													$('#exitGroup').removeClass('hidden');
												}else Box.alert('提示',rst.getMsg());
											},'POST');
										}
									})
									e.preventDefault();
									return false;    //截断发表评论的事件
								}
							});
						}
						
						var find_cid = location.href.match(/find_cid[-=](\d+)/);
						if( find_cid && find_cid[1] ){
							this.find_cid = find_cid[1];
						}
					},
					load : function(callback){
						// 确保view已创建
						this.getView();
						if( !this.isLoading ){
							this.isLoading = true;
							this.decorateLoading();
							callback && ( this.onload = callback );
							
							this.getComments(this.wbId, this.page, this.find_cid || '',  Util.getBind(this, 'onCmtsLoad'));
						}
					},
					// 创建评论列表
					createListUI : function( e ){
						this.jqCmtCt.empty();
						var data = e.getData(),
							listData = data.data;
						var htmls = [], self = this;
						
						var base = (data.page-1)* data.limit + 1;
						
						for(var i=0,l=listData.length;i<l;i++){
							var d = listData[i];
							
							d.isGroupAdmin = this.isGroupAdmin;
							
							if(typeof d == 'object'){
								d.delable = $('#btn_del')[0] ? true : false;
								var layer = base+i;
								if( layer <= 3 )
									d.floor = {1 : '沙发', 2 : '板凳', 3 : '地板'}[layer];
								
								else d.floor = layer+'楼';
								htmls[htmls.length] = self.createCmtUI.call(self, d);
							}
						}
						
						if(htmls.length){
							this.jqCmtCt.html( htmls.join('') );
							var total = data.total;
							this.jq("#commenTotal").html( "共"+total+"条评论:");
							this.jqCmtCt.cssDisplay(true);
						}else {
							this.jqCmtCt.cssDisplay(false);
							this.jqMore.cssDisplay(false);			
						}
						this.jq('ul img.replyImg').each(function(){
							var $t = $(this), src = $t.attr('_src');			
							Util.drawImage(src, 150, 200,function(obj){
								$t.attr('src',src).css({width:obj.width, height:obj.height})
							});
						});
						if(getCfg('uid'))
							X.use('usersCard',{items:this.jqCmtCt.find('.user_card')});
						
						this.itemHover(this.jqCmtCt.find('li'));
						return htmls.length;
					}
				});
				cmt.display(1);
				cmt.load( function(){
					if(this.find_cid) {
						var $cmtLi = this.jq('#cmtCt li[rel*='+this.find_cid+']');
						if( $cmtLi[0] ){
							$(document).scrollTop(cmt.cmtBox.jqInputor.offset().top - 50); 
							var uname = Util.parseKnV($cmtLi.attr('rel')).n;
							cmt.cmtBox.jqInputor.val('回复@'+uname+': ').focus();
						}
						this.find_cid = null;   //清空
					}
				});
				
			}
		})
		
		//旅游经验-回答别人的问题
		.reg('experience.consult', {
			onViewReady : function(cfg){				
				//未登陆
				if(!getCfg('uid')){
					Xwb.use('loginBox').display(1);
				}
				$('.exp-answer dt').hover(function(){
					$(this).next().find('.op').removeClass('hidden');
				},function(){
					$(this).next().find('.op').addClass('hidden');
				})
				$('.exp-answer dd').hover(function(){
					$(this).find('.op').removeClass('hidden');
				},function(){
					$(this).find('.op').addClass('hidden');
				})
				X.use('action').reg('c', function(e){
					var $parent = e.jq('tid')
					if(e.jq('e').hasClass('ico-fold')){
						$parent.find('.quest-list').fadeOut(100);
						$parent.find('.actions').fadeOut(100);
						e.jq('e').attr('class', 'ico-unfold');
					}else{
						$parent.find('.quest-list').fadeIn(100);
						$parent.find('.actions').fadeIn(100);
						e.jq('e').attr('class', 'ico-fold');
					}
				})
                .reg('sm', function(e){
					e.lock(1)
					var $parent = e.jq('tid'), $txa = $parent.find('textarea'), $btn = e.jq('e') , data = {}, qids = [];
					toState1(),count = 0;
					for(var i = 0; i < $txa.length; i++){
						var value = $txa.eq(i).val();
						if(/^\s*$/.test(value)) continue;	
						var rel = $parent.find('dd:eq(' + i + ')').attr('rel');
						qids.push(rel.slice(rel.indexOf(':')+1));
						data['text['+ count++ +']'] = $txa.eq(i).val();							
												
					}
					if(qids.length == 0){
						X.use('msgbox').tipWarn('内容不能为空');
						$txa.eq(0).focus();
						e.lock(0)
						toState0();
						return;	
					}
					qLength = qids.length;
					data.qids = qids.join(',');
					Req.replyQuestion(data, function(r){
						if(r.isOk()){
							$parent.remove();
							if(r.getData().pointCount){
								X.use('msgbox').tipWarn('恭喜你，获得' + 100*r.getData().pointCount + '游币');
							}
							if($('.exp-answer').length == 0){
								setTimeout(function(){location.href = Req.mkUrl('experience','myExp')}, 2000); 
							}
						}else{
							Box.alert('提示',r.getMsg());
						}
						toState0();
						e.lock(0)
					})
					
					function toState0(){
						$btn.attr('class', 'btn-s4');
						$txa.attr('class', 't2 style-normal style-focus');
					}
					function toState1(){
						$btn.attr('class', 'btn-s4 btn-s4-disabled');
						$txa.attr('class', 't2 style-normal');
					}
				})
				
			}
		})

		//旅游经验-求助-我的问题
		.reg('experience.my_questions_list', {
			onViewReady : function(cfg){
				$parent = $('.exp-list'), $page = $('.pagination'), data = cfg.data, list = data.question_list, html, dom = $('<div></div>'), count = 0;
				if(list.length == 0){
					$('.quests').html('<div class="tips-null-s2"><span class="ico-alert"></span><p>您还没有问过问题哦！马上来<a href="/experience.ask">了解你想去的景点</a>吧！</p></div>');
					return false;
				}
				for(var i in list){
					var html = T.parse('myQuestion1', {name:list[i].name, cover_thumb:list[i].cover_thumb, id:list[i].id});
					dom.append($(html));
					var tempDom = dom.find('.quest-list').eq(count);
					//回答者
					var heads = [], headDom = dom.find('.item').eq(count).find('.avatars');
					for(var ans in list[i].answerUsers){
						heads.push('<a href="/space.ta/id-'+ list[i].answerUsers[ans].uid +'" title="' + list[i].answerUsers[ans].nickname + '"><img alt="' + list[i].answerUsers[ans].nickname + '" src="'+ list[i].answerUsers[ans].face_xs +'"></a>')
					}
					headDom.children().append(heads.join(''));
					if(headDom.find('a').length < 15){
						headDom.children().append('<span class="ico-ftip"><i>'+ headDom.find('a').length +'</i>人回答了您的问题</span>');
					}else{
						headDom.children().append('<span class="ico-unfold" rel="e:f" title="展开"><i>'+ headDom.find('a').length +'</i>人回答了您的问题</span>');
						headDom.children().find('a:gt(14)').addClass('hidden');
						X.use('action').reg('f', function(e){
							e.jq('e').parent().find('a:gt(14)').removeClass('hidden');
							e.jq('e').replaceWith('<span class="ico-fold" rel="e:uf" title="收起">收起</span>');
						}).reg('uf', function(e){
							e.jq('e').parent().find('a:gt(14)').addClass('hidden');
							e.jq('e').replaceWith('<span class="ico-unfold" rel="e:f" title="展开"><i>'+ e.jq('e').parent().find('a').length +'</i>人回答了您的问题</span>');
						})
						
					}
					
					//回复列表
					for(var y in list[i].questions){
						var a = list[i].questions, c = 0;
						var html = T.parse('myQuestion2', 
						{
							//title:a[y].text,
							qid:a[y].id
						});
						tempDom.append($(html));
						tempDom.find('dt:last').text(a[y].text);
						for(var z in a[y].answers){
							if(tempDom.find('.answer-list:last').children().length > 2) break;
							var b = a[y].answers;
							var html = T.parse('myQuestion3', 
							{
								id : b[z].id,
								face : b[z].user.face_xs,
								nickname : b[z].user.nickname,
								//text : b[z].text,
								tid : b[z].user.id,
								time : X.use('getTimeString').fn(b[z].create_time)
							});
							tempDom.find('.answer-list:last').append($(html));
							tempDom.find('li:last p').text(b[z].text);
							if(b[z].thx_state){
								tempDom.find('.answer-list:last').find('.operate').last().html('已感谢');
							}
						}
						//console.log(tempDom.find('.answer-list:last li').length);
						if(!tempDom.find('.answer-list:last li').length){
							tempDom.find('.msg-cont:last').html('暂时没有回复');
						}
						if(a[y].ans_num > 3){
							tempDom.find('.msg-box:last').append('<div class="more"><a href="#" rel="e:ga">查看全部</a></div>')
						}
					}
					count++;
				}
				$parent.children().remove();
				$parent.append(dom.html());
				$parent.find('li').hover(function(){
					$(this).find('.report').removeClass('hidden');
				},function(){
					$(this).find('.report').addClass('hidden');
				})
				X.use('action').reg('thx', function(e){
					Req.expThanks(e.get('aid'), function(r){
						if(r.isOk()){
							e.jq('e').parent().html('已感谢');
						}else{
							Box.alert('提示',r.getMsg());
						}
					})

				}).reg('ga', function(e){
					var $parent = e.jq('qid').find('.answer-list');
					if($parent.data('s')){
						e.jq('qid').find('li:gt(2)').removeClass('hidden');
						e.jq('e').parent().html('<a href="#" rel="e:cl">收起</a>');
					}else{
						e.lock(1);
						$parent.html('<li><div class="loading"></div></li>')
						Req.getReply(e.get('qid'), function(r){						
							if(r.isOk()){
								var data = r.getData(), dom = $('<div></div>'), list = data.answers;
								for(var i in list){
									var html = T.parse('myQuestion3', 
									{
										id : list[i].id,
										face : list[i].user.face_xs,
										nickname : list[i].user.nickname,
										//text : list[i].text,
										tid : list[i].user.id,
										time : X.use('getTimeString').fn(list[i].create_time)
									});								
									html = $(html)
									if(list[i].thx_state){
										html.find('.operate').html('已感谢');
									}
									html.find('p').text(list[i].text);
									dom.append(html)
								}
								dom = dom.find('li');
								$parent.data('s',1).html(dom);
								e.jq('e').parent().html('<a href="#" rel="e:cl">收起</a>');
								e.jq('qid').find('li').hover(function(){
									$(this).find('.report').removeClass('hidden');
								},function(){
									$(this).find('.report').addClass('hidden');
								})		
							}else{
								Box.alert('提示',r.getMsg());
							}
							e.lock(0);
						})
					}
				}).reg('cl', function(e){
					e.jq('qid').find('li:gt(2)').addClass('hidden');
					e.jq('e').parent().html('<a href="#" rel="e:ga">查看全部</a>')
				})
				
			}
		})
		//旅游经验-我的经验
		.reg('experience.my_exp_list', {
			onViewReady : function(cfg){
				$parent = $('.exp-list'), data = cfg.data, list = data.exp_list, html, dom = $('<div></div>'), count = 0;
				if(list.length == 0){
					$('div.my-exp').html('<div class="tips-null-s2"><span class="ico-alert"></span><p>您还没有分享过您的旅行经验哦！赶快来分享吧，赚取<span class="txt-hl">游币</span>和<span class="txt-hl">勋章</span>，更有丰富礼品等着您哦！</p><p><a href="/experience.share">马上分享</a></p></div>');
					return false;
				}
				for(var i in list){
					var html = T.parse('myExp', {name:list[i].name, cover_thumb:list[i].cover_thumb, id:list[i].id});
					dom.append($(html));
					for(var y in list[i].answers){
						var a = list[i].answers;
						var html = T.parse('myExpIn', 
						{
							//title:a[y].questions.text, 
							text:a[y].text, 
							id:a[y].id,
							time:X.use('getTimeString').fn(a[y].create_time)
						});
						dom.find('.quest-list').eq(count).append($(html));
						dom.find('.quest-list').eq(count).find('p:last span').text(a[y].text);
						dom.find('.quest-list').eq(count).find('dt:last').text(a[y].questions.text);
					}
					count++;
				}
				
				$parent.children().remove();
				$parent.append(dom.html());
			}
		})
		//旅游经验-求助-添加问题1
		.reg('experience.ask_step1', {
			onViewReady : function(cfg){
				var data = cfg.data, list = data.qaList.questions, spot = data.spotsInfo, _this = this, spotName,
				$parent = $('#qlist'), count = 0, $tip = $('#spotsTip'), initSign, sourceLength;
				
				if(spot.length != 0){
					for(var i in spot){
						$('#spots').val(spot[i].name);
						$('#spots_id').val(spot[i].id);
						spotName = spot[i].name;
					}
					$('form').find('.action').append($('<p><a href="#" rel="e:a">+添加</a></p>'));
					$('form').find('.actions').prepend($('<p><a href="#" rel="e:a">+添加</a></p>'));
					$('form').find('.actions .btn-s4').removeClass('btn-s4-disabled');
					$('form').find('.actions .btn-s4').attr('rel','e:sm');
					dis();
				}else{
					
				}
				var search = X.use('search', {
					inputor : $('#spots'),
					view : this.jq('#spotsBox')[0],
					catchClick: true,
					onEnter : function(e, row){
						$tip.addClass('hidden');
						this.inputor.val(row.name);
						$('#spots_id').val(row.id);
						$parent.children().find('input').val('');
						spotName = row.name;
						$('#spots_id').blur(function(){
							
						})
						Req.askQuestion(row.id, 4, function(r){
							if(r.isOk()){
								list = r.getData().questions;
								sourceLength = 0;
								for(var i in list){
									sourceLength ++;
								}
								if(!initSign){
									$('form').find('.actions').prepend($('<p><a href="#" rel="e:a">+添加</a></p>'))
									$('form').find('.actions .btn-s4').removeClass('btn-s4-disabled');
									$('form').find('.actions .btn-s4').attr('rel','e:sm');
									initSign = true;
								}
								
								dis();
							}else{
								if(r.raw.errno == 1105001){
									Box.alert('提示','对不起，每天只能提问两个景点');
								}else{
									Box.alert('提示',r.getMsg());
								}
								
							}
						})
						
					},
					affixfun: function(){ 
						//alert(1)
					}
				});
				function dis(){
					var html = [];
					count = 0;
					for(var i in list){
						count++;
						html.push(T.parse('askStep1', {id:count-1, count:count, text:list[i].text}))
					}
					$parent.children().remove();
					$parent.append($(html.join('')));
					$parent.children().hover(function(){
						$(this).find('.ico-close-btn').removeClass('hidden');
					},function(){
						$(this).find('.ico-close-btn').addClass('hidden');
					})
				}
				
				//绑定事件
				var act = Xwb.use('ActionMgr',{
					target : _this.jq()
				}).reg('a', function(e){
					if(count >= 20){
						Box.alert('提示','对不起，每次最多提20个问题');
						return false;
					}
					count++;
					var obj = $(T.parse('askStep1', {id:count-1, count:count}))
					$parent.append(obj);
					$(obj).hover(function(){
						$(this).find('.ico-close-btn').removeClass('hidden');
					},function(){
						$(this).find('.ico-close-btn').addClass('hidden');
					})
				}).reg('d', function(e){
					count--;
					e.jq('id').remove();
					var c = $parent.children();
					for(var i=0; i < c.length; i++){
						c.eq(i).find('label').html('问题'+ (i+1) + '：');
						c.eq(i).attr('rel', 'id:' + i);				
					}
					
				}).reg('sm', function(e){
					var sid = $('#spots_id').val();
					if($('#spots').val() == spotName){
						var raw = $parent.find('input'), d = {}, count= 0, $f = $('form');
						for(var i = 0; i < raw.length; i++){
						if(!/^\s*$/.test(raw.eq(i).val())){
							var l = Util.byteLen(raw.eq(i).val());
							if(l < 10 || l > 60){
								raw.eq(i).focus();
								X.use('msgbox').tip('提问内容限制5到30个汉字');
								return false;
							}
							d['questions[' + count++ + ']'] = raw.eq(i).val();
							}						
						}
						$.extend(d, {sid:sid});
						e.lock(1);
						Req.submitQuestion(d, function(r){
							if(r.isOk()){
								$f.find('[name=spots_id]').remove();
								$f.find('[name=recom_uids]').val(r.getData().recom_uids.join(','))
								$f.find('[name=group_id]').val(r.getData().group_id);
								$f[0].submit()
							}else{
								Box.alert('提示',r.getMsg());
								e.lock(0);
							}
						})
					}else{
						$tip.removeClass('hidden');
					}
					return false;
				})
				
				$('#form_btn').click(function(){
					
				
				})
				//提交
				/*
				Xwb.use("Validator", {
                form: $("form"),
                trigger: "#form_btn",
     			onsuccess : function(data, next){
				
				    var $f = $("form"), self = this;
					var raw = $parent.find('input'), d = {}, count= 0, sid = $('#spots_id').val();
					self.lock(1)
					for(var i = 0; i < raw.length; i++){
						if(!/^\s*$/.test(raw.eq(i).val())){
							d['questions[' + count++ + ']'] = raw.eq(i).val();
						}						
					}
					$.extend(d, {sid:sid});
					Req.submitQuestion(d, function(r){
						if(r.isOk()){
							$f.find('[name=spots_id]').remove();
							$f.find('[name=recom_uids]').val(r.getData().recom_uids.join(','))
							$f.find('[name=group_id]').val(r.getData().group_id)
							$f[0].submit()
						}else{
							Box.alert('提示',r.getMsg());
							
						}
						self.lock(0)
						
					})
					return false;
					
     			}
				});
				*/
			}
		})
		//旅游经验-求助-添加问题2
		.reg('experience.ask_step2', {
			onViewReady : function(cfg){
				ui = this.getUI().view;
				$(ui).find('.pic').hover(function(){
					$(this).find('.intro').fadeIn(300);
					},
					function(){
						$(this).find('.intro').fadeOut(300);
					}
				)
				/*
				X.use('action').reg('s', function(e){
					e.lock(1);
					var question = $('[name=questions]').val(),
						uid = $('[name=recom_userId]').val(),
						sid = $('[name=sid]').val();
					Req.submitQuestion(question, uid, sid, function(r){
						if(r.isOk()){
								
							
						}else{
							Box.alert('提示',r.getMsg());
						}
						
						e.lock(0);
					})
				})
				*/
			}
		})
		//旅游经验-分享经验
		.reg('experience.share', {
			onViewReady : function(cfg){
				var data = cfg.data.qaList, winExpert, curType = '', curId = '', $btn = $('#change .btn-s7'), Html = '', q = data.questions, ui = this.getUI().view, $ui, page = data.next_cursor, $parent = $('.exp-quests'), count = cfg.data.counts.a_num + 1;
				//超过配额
				if(cfg.data.qaList.errno == 105001 || cfg.data.qaList.errno == 105002){
					$parent.find('.actions').remove();
					$parent.find('.hints').remove();
					$('.exp-info .actions').remove();
					$parent.find('.tips-null-s2').removeClass('hidden').find('p').html('你今天已经分享了超过<span class="txt-hl">50个</span>问题啦，休息一下吧，可以去<a href="#">别的地方</a>看看。');	
					return false;
				}
				//木有问题了
				if(cfg.data.qaList.questions.length == 0){
					$parent.find('.actions').remove();
					$parent.find('.hints').remove();
					$('.exp-info .actions').remove();
					$parent.find('.tips-null-s2').removeClass('hidden').find('p').html('你已经分享了<span class="txt-hl">' + cfg.data.counts.a_num + '条</span>经验了，你可以再<a href="#" rel="e:fm">添加</a>一些去过和想去的地方。');
					//无足迹时添加足迹
					X.use('action').reg('fm', function(e){
						var html = T.parse('expFootmark');
						function setHover(obj){
							obj.hover(function(){
								$(this).find('.ico-close-btn').removeClass('hidden');
							},function(){
								$(this).find('.ico-close-btn').addClass('hidden');
							})
						}
						$('.main-cont').find('.exp-quests').remove();
						$('.main-cont').find('.exp-info').remove();
						$('.main-cont').append(html);
						//setHover($('.form').find('.row'));
						
						//window.Req = Req;
						X.use('action').reg('s',function(e){
							e.lock(1);
							var $row = $('.form').find('.row'), data = {};
							data.p = [];
							for(var i in $row){
								var num = $row.eq(i).data('s')
								if(num){
									data.p.push(num + ':2');
								}
							}
							if(data.p.length > 0){
								data.p = data.p.join(',')
								Req.batchSetFm(data, function(r){
									if(r.isOk()){
										window.location.reload();
									}else{
										Box.alert('提示',r.getMsg());
									}
									e.lock(0)
								})
							}else{
								X.use('msgbox').tipWarn('请输入内容');
								$('.form').find('input:eq(0)').focus();
								e.lock(0);
							}
							
						}).reg('d',function(e){
							e.jq('e').parent().remove();
						}).reg('a',function(e){
							var html = T.parse('expFootmarkRow');
							html = $(html);
							html.insertBefore($('.form').find('.actions'));
							setHover(html);  
							var search = X.use('search', {
								inputor : html.find('input'),
								view : html[0],
								catchClick : true,
								defaultText : '',
								onEnter : function(e, row){
									
									this.inputor.val(row.name);
									html.data('s', row.id);
									
									
								}
							})
						})
						X.use('action').doAct($('.form').find('.actions a:eq(0)'));
						
				
					})
					return false;
				}
			
					function disQ(sign){
						if(sign){
							var index = count;
							for(var i in q){	
							Html += '<dt rel="id:' + q[i].id + '">'+ index++ + '.' + q[i].text + '</dt>'
							+ '<dd rel="id:'
							+ q[i].id
							+ ',df:'
							+ q[i].guide
							+ '"><div class="msg-box clear"><span class="arrow">'
							+ '<span class="arrow-in">◆</span>◆</span><div class="msg-cont clear">'
							+ '<a href="#" class="btn-s4" rel="e:expa"><span>提交</span></a>'
							+ '<textarea class="t1 style-normal style-focus">'
							+ q[i].guide
							+ '</textarea>'
							+ '</div>'
							+ '</div>'
							+ '<span class="op hidden"><a href="#" class="sp" rel="e:expdl">不回答</a></span>'
							+ '<span class="prize hidden">+10000游币</span>'
							+ '</dd>';            
							}
							$ui.html(Html);	
							$parent.find('textarea').focus(function(){
								var val = $(this).parent().parent().parent().attr('rel');
								val = val.slice(val.indexOf('df:')+3);
								if($(this).val() == val){
									$(this).val('');
								}
							}).blur(function(){
								var val = $(this).parent().parent().parent().attr('rel');
								val = val.slice(val.indexOf('df:')+3);
								if($(this).val() == ''){
									$(this).val(val);
								}
							});
							$parent.find('dt').hover(function(){
								$(this).next().find('.op').removeClass('hidden');
							},function(){
								$(this).next().find('.op').addClass('hidden');
							})
							$parent.find('dd').hover(function(){
								$(this).find('.op').removeClass('hidden');
							},function(){
								$(this).find('.op').addClass('hidden');
							})
							$parent.find('.quest-list').removeClass('hidden');
							$parent.find('.tips-null-s2').addClass('hidden');
								
						}else{
							$parent.find('.quest-list').addClass('hidden');
							$parent.find('.tips-null-s2').removeClass('hidden');	
							$parent.find('.actions a').addClass('hidden');
						}
						
					}
					
					if(page == -1){
						$parent.find('.actions a').addClass('hidden');
					}
					$(ui).remove();
					$ui = $('.quest-list');
					disQ(1);
					
					//选择擅长问题
					X.use('action').reg('expex', function(e){
						if(!winExpert){
							winExpert = X.use('expExpert',{
								type : cfg.data.qaType,
								spots : cfg.data.bgSptos,
								callback : function(){
									$parent.find('.loading').removeClass('hidden');
									Req.getExpQuestion(curType = winExpert.getType().id, curId = winExpert.getId().id, data.count, page = 0, function(r){
										if(r.isOk()){
											$parent.find('.quest-list').children().remove();
											if(r.getData().questions.length == 0){
												disQ(0);
											}else{
												Html = '';
												q = r.getData().questions;
												$('#myExpert').html(winExpert.getId().val + '，' + winExpert.getType().val);
												if(r.getData().next_cursor == -1 && r.getData().total < 10){
													$parent.find('.actions a').addClass('hidden');
												}else{
													if(r.getData().next_cursor == -1){
														page = 0;
													}else{
														page = r.getData().next_cursor;
													}
													$parent.find('.actions a').removeClass('hidden');
												}
												disQ(1);
											}
										}else{
											Box.alert('提示',r.getMsg());
										}
										winExpert.display(0);
										$parent.find('.loading').addClass('hidden');
									})
								}
							});
						}else{
							winExpert.display(1);
						}					
					}).reg('expn', function(e){
						e.lock(1);
						$parent.find('.loading').removeClass('hidden');
						Req.getExpQuestion(curType, curId, data.count, page, function(r){
							if(r.isOk()){
								$parent.find('.quest-list').children().remove();
								if(r.getData().questions.length == 0){								
									disQ(0)
									e.lock(0);
								}else{
									Html = '';
									q = r.getData().questions;
									if(r.getData().next_cursor == -1 && r.getData().total < 10){
										$parent.find('.actions a').addClass('hidden');
									}else{
										if(r.getData().next_cursor == -1){
											page = 0;
										}else{
											page = r.getData().next_cursor;
										}
										$parent.find('.actions a').removeClass('hidden');
									}
									disQ(1);
								}
							}else{
								Box.alert('提示',r.getMsg());
							}
							$parent.find('.loading').addClass('hidden');
							e.lock(0);
						})
					}).reg('expa', function(e){
						e.lock(1);
						var id = e.get('id'), $el = $(e.getEl('id')), $txa = $el.find('textarea'), text = $txa.val(), df = e.get('df'), l = Util.byteLen(text);
						if(text == df){
							Box.anchorTip(e.jq('e'), '请输入内容');		
							e.lock(0);
							return false;
						}
						if(/^\s*$/.test(text) || l < 10){
							Box.anchorTip(e.jq('e'), '不能少于5个汉字');		
							e.lock(0);
							return false;
						}
						$txa.removeClass('style-focus');
						$el.find('.btn-s4').addClass('btn-s4-disabled');
						Req.expAnswer(id, text, function(r){
							if(r.isOk()){
								count++;
								var data = r.getData();
								$el.find('.prize').removeClass('hidden').html(data.notice);	
								$el.find('.prize').animate({marginTop:'-30px', opacity:0}, 1000, 'swing');
								$el.find('.msg-cont').children().remove();
								$el.find('.msg-cont').html('<p>'
								+ '<span></span>'
								+ '<a href="#" rel="e:expe">[编辑]</a></p>');
								$el.find('.msg-cont span').text(text);
								e.jq('id').prev().find('a').remove();
								
							}else{
								$txa.addClass('style-focus');
								$el.find('.btn-s4').removeClass('btn-s4-disabled');
								Box.alert('提示',r.getMsg());
							}
							e.lock(0);
						})
						
					})	
			}
		})
        //小组帖子发表页
        .reg('group.topic_edit_editor', {
            ui : {
                cls : X.mod.GroupPost
            },
            
            onViewReady : function(cfg) {
                var ui = this.getUI(),
                    data = cfg.data || {};
                if (data.tpl_type == 'topic_edit') {
                    data.title = $('#title').val();
                    ui.setData(data)
                    .mode = 1;
                } else {
                    //分享选项 
                    X.use('ThirtyAccountCheckList', {
                        view : '#share'
                    })
                }
            }
        })
		
		.reg('album.albumList' ,function(){ 
			return new ImpressPletBase({
				insertTag : 'ul.col',
				makeUrl : true,
				album : true,
				row : 4,
				regAction : function(){				
					var ui = this.getUI(), $list = ui.jq('div.photo-list');
					this.hasPage = !ui.jq('.tips-null-s2').length;
					X.use('ActionMgr', {target : $list}).reg('cmt',function(e){
						var t = e.get('t'), $src = $(e.src), src = $src.attr('_src');
							X.cfg.youji = e.get('yid');
						var param = {hasCmt : e.get('type') == 3?false:true, srcList:X.getCfg('srcList'), srcListIsString:false},
							box = X.use('youjiImg', param);
							box.reply(src,e.get('w'));		
							box.setOffset();							
							e.get('focus') == '1' && box.cmtBox.jqInputor.focus();
							box.pid = e.get('id');
							box.yid = e.get('yid');
					});
					
					var morePlace = ui.jq('#morePlace'), operate = ui.jq('#operate');
					operate.click(function(e){
						e.preventDefault();
						if(operate.attr('rel') == '0'){
							operate.attr('rel', 1);
							operate.html('<i><<</i>收起');
							morePlace.cssDisplay(1);
						}else{
							operate.attr('rel', 0);
							operate.html('展开<i>>></i>');
							morePlace.cssDisplay(0);
						}
					})
					
				},
				insert : function( data ){
					data = data.list || data;
					var imgHeightArr = [],
						srcList = [],
						len = data.length,
						sum = 0;    //这一批印象条目所包含图片的高度的总和
					if( len < 1 ) return ;
					if(!X.getCfg('srcList')){
						X.cfg.srcList = srcList;
					}else{
						srcList = X.getCfg('srcList');
					}
					
					for(var i=0;i<len;i++){
						var cd = data[i], real = X.util.getRealSize(cd.img_width, cd.img_height, 188, 1000);
						var ih = real[1], 
							iw = real[0],
							addsHeight = 25;   //附加高度,包括边距,填充...
						cd.img_width = iw;
						cd.img_height = ih;
						if( iw > 188 )
							ih = ih*(188/iw);
						imgHeightArr[i] = ih + addsHeight;
						sum += imgHeightArr[i];							
						srcList.push({url:data[i].img_data.original_pic.url,yid:data[i].youji_id,pid:data[i].img_data.id,type:data[i].img_data.type});
					}
					var $cols = this.$cols,
						tempArr = [];
						rest = $cols.eq(2).height() - $cols.eq(3).height(),  //当前两列的差值
						tarHeight = sum/this.row ||(sum - Math.abs(rest))/this.row,  //较高的那一列，应填充的高度
						subset = Util.subsetSplit(imgHeightArr, tarHeight);   //具体查看subsetSplit的返回
					

					if(len<this.row){
						for(var i=0;i<len;i++){
							this.insertInto(data[i].html, $cols.eq(i), data[i].img_height, data[i].img_width);
						}
						return;
					}
					this.selectOnce(data, 0, len, imgHeightArr, $cols, subset);


					subset = Util.subsetSplit(imgHeightArr, tarHeight);
					
					len = data.length;
					this.selectOnce(data, 1, len, imgHeightArr, $cols, subset);
					
					len = data.length;

					subset = Util.subsetSplit(imgHeightArr, tarHeight);
					
					var shorter = 0, higher = 1;
					if( rest > 0 ) {
						shorter = 1;
						higher = 0;
					}
					for(var i=0 ;i<len;i++){
						if( subset[i] == 1 )
							this.insertInto(data[i].html, $cols.eq(higher+2), data[i].img_height, data[i].img_width);
						else 
							this.insertInto(data[i].html, $cols.eq(shorter+2), data[i].img_height, data[i].img_width);
					}
				},
				
				insertInto : function(html, col, h, w){
					if(html){
						var li = $(html).appendTo(col), img = li.find('img');
						img.width(w);
						//img.height(h);
					}
				},
				
				selectOnce : function(data, ul_num, len, imgHeightArr, $cols, subset){					
					var first = 1;
					for(var i=0, k=0;i<len;i++){
						if(first == subset[i]){
							this.insertInto(data[i-k].html, $cols.eq(ul_num), data[i-k].img_height, data[i-k].img_width );
							data.splice(i-k, 1);
							imgHeightArr.splice(i-k, 1);
							k++;
						}
					}
					
					return data;
				},
				
				page : 1,
				
				lock : false,
				
				getUrl : function(){
					this.page++;
					return Req.jsAPI('albumApi','userAlbumList',{page:this.page, user_spots_id:this._data.user_spots_id, uid : this._data.uid||''})
				},

				setScroll: function(){
					var self = this;
					if(this.hasPage)
						$(window).bind('scroll',function(){						
							if( $(document).scrollTop() + Util.getClientHeight() > $(document.body).height() - 50 ){
								if( self.lock )	return false;
								self.lock = true;
								self.showLoading();
								Req.q( self.getUrl(), {}, function(r){
									if(r.isOk()){
										var rstData = r.getData();
										if(rstData && rstData.list){
											self.insert( rstData.list );
											self.lock = false;
										}
									}
									self.hideLoading();								
								})
							}
						});
				}
				
			}) 
		})
		
		//码头未登录页
		.reg('center.nolog_guide', {
			onViewReady : function(cfg){
				if(Util.ie6){
					var v = this.getUI(), imgs = v.jq('div.pic-cont img');
					for(var i=0,len = imgs.length;i<len;i++)
						Util.drawImage(imgs[i], 490, 1500);					
				}
			}			
		})
        
        .reg('comment.ziyouji', CommentPipe)
		
		.reg('show.footprint', {
			onViewReady : function(cfg){
				var ui = this.getUI(),
                    data = cfg.data,
                    foots = data.footmarks;
				//异步加载LoadBaiduMap
				X.on('pipe.end', function(){				
					X.use('LoadBaiduMap').initUI({
							view :ui.getView(),
							rightLists : false, //右边列表
							canClick : false,
							hasNav : false
						}, this, foots);
				});	
			}
		})
		
		.reg('spots.index_focus_pic', {
			onViewReady : function(cfg){
				var ui = this.getUI();
				$('#slider').fader({
					Main:'#sliderUL',
					Control:'#sliderControl',
					ControlCss:'cur',
					img:'img[_src]',
					callback:function(page){},
					runningFn : function(){
						$('#info div.desc:visible').fadeOut(300,function(){
							$('#info>div.desc').eq($('#sliderControl li.cur').index()).show();
						});
						ui.jq('div.intro:visible').fadeOut(300,function(){
							ui.jq('div.intro').eq($('#sliderControl li.cur').index()).show();
						});						
					},
					split : 3000
				});
			}	
		})
		
		.reg('show.idx_show', {
			onViewReady : function(cfg){
				$('#slider').fader({
					Main:'#sliderUL',
					Control:'#sliderControl',
					ControlCss:'current',
					img:'img[_src]',
					callback:function(page){},
					runningFn : function(){},
					split : 3000
				});
			}				
		})
		//周边行程
		.reg('trip.index_focus_pic', {
			onViewReady : function(cfg){
				$('#slider').fader({
					Main:'#sliderUL',
					Control:'#sliderControl',
					ControlCss:'current',
					img:'img[_src]',
					callback:function(page){},
					runningFn : function(){
						$('#info div.desc:visible').fadeOut(300,function(){
							$('#info>div.desc').eq($('#sliderControl>a.current').index()).show();
						})
					},
					split : 3000
				});
			}				
		})
		
		.reg('spots.common_spot_dynamics', Util.create(Pagelet, $.extend(SpotsPipe,{onViewReady : function(cfg){
                var ui = this.getUI(),
                    data = cfg.data;
				var loading = this.loading = ui.jq('#sloading');
                var cols = this.cols = [
                    ui.jq('#col_1'),
                    ui.jq('#col_2'),
                    ui.jq('#col_3')
                ];
				this.colCount = 3;
                var htmls = data.li_html;
				this.wbCount = htmls.length;
                
					
				if( this.wbCount.length !== 0){
					loading.cssDisplay(0);
				    this.createItems( htmls, Util.getBind(this, 'toLoadedSeq'));
				}
                else{
					$('#feedList').after('<div align="center">没有数据</div>');
					loading.cssDisplay(0);
				}
		}})))
		
		.reg('trip.index_recom_hot_youji', {
			onViewReady : function(cfg){
				var ui = this.getUI();
				X.use('ShowInfo', {view:ui.jq('#showInfo')[0]}).display(1);			
			}				
		})
		.reg('spots.index_aside_hot_spot',{
			onViewReady : function(cfg){
				var ui = this.getUI();
				X.use('ShowInfo', {view:ui.jq('#showInfo')[0]}).display(1);			
			}	
		})
		.reg('trip.search_searchbox', {
			onViewReady : function(cfg){
				var ui = this.getUI();
				ui.jq('#tagSearchForm>a').click(function(e){
					e.preventDefault();
					var v = $.trim(ui.jq('.input-txt').val());
					if(v){
						ui.jq('form').submit();
					}
				});
			}
		})
		.reg('spots.search_searchbox', {
			onViewReady : function(cfg){
				var ui = this.getUI();
				var sb = ui.jq('div.search-box-s3');
				sb.find('a.btn-s4').click(function(e){
					e.preventDefault();
					var v = $.trim(sb.find('.input-txt').val());
					if(v){
						window.location.href = Req.mkUrl('search','spots',{q:v})
					}
				});
			}
		})
		//酒店
		.reg('hotel.focus_map', {
			onViewReady : function(cfg){
				$('#slider').fader({
					Main:'#sliderUL',
					Control:'#sliderControl',
					ControlCss:'cur',
					controlAlink : true,
					img:'img[_src]',
					callback:function(page){},
					runningFn : function(){},
					split : 3000
				});
			}	
		})
		
		//专题瀑布流
		.reg('special.home_list', {
			onViewReady : function(cfg){
					var ui = this.getUI(), view = ui.view, navs = ui.jq('#tabBar>span'), items = [];
					for(var i=0;i<navs.length;i++){
						var rel = '';
						if(navs.eq(i).attr('rel')){
							rel = Util.parseKnV(navs.eq(i).attr('rel'));							
						}else{
							rel = Util.parseKnV(navs.eq(i).find('a').attr('rel'));
						}
						items.push({id:'#show-'+i,type:rel.gid});
					}
					X.use('SwitcherExt', {	
						//items :[{id:'#show-0',type:'0'},{id:'#show-1',type:'1'}, {id:'#show-2', type:'2'}, {id:'#show-4', type:'4'}, {id:'#show-4', type:'4'}],
						items : items,
						actoinObj : 'tabBar',
						view : ui.view,
						cur : 0,
						setTab : function(o){
							var cs = o.parent(), p = cs.parent(), s = p.find('em').parent()
							, oldRel = s.attr('rel'), oparam = Util.parseKnV(oldRel)
							, newRel = o.attr('rel'), nparam = Util.parseKnV(newRel) 
							, oldObj = this.jq('#show-'+oparam.gid).data('tc');
							if(oldObj) oldObj.enScroll = false;
							s.replaceWith('<span><a href=# rel="'+oldRel+'">'+s.text()+'</a></span>');		
							cs.replaceWith('<span rel="'+o.attr('rel')+'" class="cur"><em>'+o.text()+'</em></span>');	
							return true;
						},
						
						getPart : function(data){						
							this.createDiv(data);
							this.getPageData(data);							
						},
						
						getPageData : function(info){
							var self = this;
							Req.q(Req.jsAPI('specialApi','home_list'), {gid:info.type,page:1,count:15}, function(r){								
								if(r.isOk()){
										var data = r.getData();
										if(data.li_html.length == 0){
											self.jq(info.id).html('<div align="center">没有数据</div>');
										}else
											createTab(self.jq(info.id), data);
								} else {
										
								}
							});
						},
						
						createDiv : function(info){
							this.jq('#showPart').append('<div class="tour-bd place-show" id="'+(info.id.replace("#",""))+'">'+ 
												'<ul id="col_1" class="col"></ul>'+ 
												'<ul id="col_2" class="col"></ul>'+ 
												'<ul id="col_3" class="col"></ul>'+ 
											'</div>');
						}
					}); 
					
					var createTab = function(tabContent, data){
						var tc = Util.create(X.ui.Base, $.extend(SpotsPipe,{
							onViewReady : function(cfg){
								var loading = this.loading = $('#sloading');
								var cols = this.cols = [
									tabContent.find('#col_1'),
									tabContent.find('#col_2'),
									tabContent.find('#col_3')
								];
								this.colCount = 3;
								var htmls = data.li_html;
								this.wbCount = htmls.length;
								
								if( this.wbCount.length !== 0){
									loading.cssDisplay(0);
									this.createItems( htmls, Util.getBind(this, 'toLoadedSeq'));
								}else{
									$('#feedList').after('<div align="center">没有数据</div>');
									loading.cssDisplay(0);
								}
								this.url = data.url;
								this.enScroll = true;
								this.setScrollLoad();								
							},
							setScrollLoad : function(){
								var self = this;
								$(window).bind('scroll',function(){
									if( !self.enScroll || self.times <= 0 || self.url == '') return ;
									if( $(document).scrollTop() + Util.getClientHeight() > $(document.body).height() - 50 ){						
										self.enScroll = false;
										self.loading.cssDisplay(1);
										Req.q(self.url, {}, function(r){
											self.enScroll = true;
											self.hideLoading();
											if(r.isOk()){
												var data = r.getData();
												self.url = data.url;
												self.createItems( data.li_html, Util.getBind( self, 'toLoadedSeq'));
											} else {
												self.hasNextPage = false;
												$(window).unbind('scroll');
											}
										});
									}
								})
							}
							}));
							var newClass = new tc();
							tabContent.data('tc', newClass);
							newClass.display(1);	

					}
					
					createTab(ui.jq('#show-0') ,cfg.data);
			}	
		})
		
		//首页焦点图　
		.reg('index.banner', {
			onViewReady : function(cfg){
				$('#slider').fader({
					Main:'#sliderUL',
					Control:'#sliderControl',
					ControlCss:'cur',
					img:'img[_src]',
					callback:function(page){},
					runningFn : function(){
						$('#info div.desc:visible').fadeOut(300,function(){
							$('#info>div.desc').eq($('#sliderControl>li.cur').index()).show();
						})
					},
					split : 3000
				});
				
			}			
		})
		
		.reg('index.user_show', {
			onViewReady : function(){
				var v = this.getUI();
				$('#focusIndex li').each(function(i){
					var _t = $(this).mouseover(function(e){
						if(!_t.hasClass('cur')){
							var oindex = v.jq('#focusIndex .cur').index(), nindex = _t.index();
							v.jq('#focusIndex .cur').removeClass('cur');
							_t.addClass('cur');
							v.jq('#focusPic li:eq('+oindex+')').cssDisplay(0);
							v.jq('#focusPic li:eq('+nindex+')').cssDisplay(1);
							v.jq('.talent-intro:eq('+oindex+')').cssDisplay(0);
							v.jq('.talent-intro:eq('+nindex+')').cssDisplay(1);
						}
					})	
				})
			}
			
		})
})(Xwb, $);
